gpt4 book ai didi

javascript - JSON.stringify(2) == "2"可能返回 false 是否正确?

转载 作者:行者123 更新时间:2023-12-03 00:30:12 24 4
gpt4 key购买 nike

我发现在 Opera 11.50 上的表达式

 JSON.stringify(2)

返回一个对象

  • typeof 返回“string”
  • constructor.nameString
  • charCodeAt(0) 为 50
  • 长度为1

但是还是

alert(JSON.stringify(2) == "2")

在 Opera 中显示“false”(使用 === 也会发生同样的情况)。

这是一个错误还是什么?

我发现使其比较等于“2”的唯一方法是调用.substr(0)(例如,即使添加空字符串仍然比较不同)。

最佳答案

这看起来绝对是一个错误。

来自 ECMAScript 5.1 规范:

Conforming implementations of JSON.parse and JSON.stringify must support the exact interchange format described in this specification without any deletions or extensions to the format. This differs from RFC 4627 which permits a JSON parser to accept non-JSON forms and extensions.

还有:

JSON.stringify produces a String that conforms to the following JSON grammar. JSON.parse accepts a String that conforms to the JSON grammar

它可能以某种方式将字符串包装在“JSONText”类型对象中,该对象仍然具有 typeofstring 但这看起来很奇怪。

我肯定认为在这种情况下以下实现是正确的:

JSON.stringify(2) == "2" && JSON.stringify(2) === "2" && JSON.stringify(2) == 2 && JSON.stringify(2) !== 2;
true

根据@6502(参见评论),这是true:
Chrome ;火狐浏览器; IE9; iPad Safari; OSX Safari; N1 Android 浏览器

ECMAScript 5.1 规范文档:http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf

关于javascript - JSON.stringify(2) == "2"可能返回 false 是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7058148/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com