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

标签 javascript opera

我发现在 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/

相关文章:

javascript - 当与 Webpack 捆绑在一起时,任何 Node.js HTTP 请求模块都可以在服务器和浏览器中工作?

javascript - jp@gc 的脚本 - WebDriver Sampler

javascript - 从 selenium/protractor javascript 中的 span 元素中提取内部

javascript - Opera 上的 JS 函数问题

html - 为什么在 IE 和 Opera 中我的 div 之间没有显示页面背景色?

javascript - 嵌套的 $(document).ready() 和 $(window).load() 事件之间的区别

javascript - 从输入到不同 div 的多个图像预览

css - Opera 中的模拟 webkit-transform

javascript - Opera post(GET)s URL 的散列片段

javascript - Opera 26 (chromium) 中的 getUserMedia 来自本地主机被阻止