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

发布于 2024-11-29 12:35:57 字数 535 浏览 7 评论 0 原文

我发现在 Opera 11.50 上,表达式

 JSON.stringify(2)

返回一个对象,其中

  • typeof 返回 "string"
  • constructor.nameString< /code>
  • charCodeAt(0) is 50
  • length is 1

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

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

这是一个错误还是什么?

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

I've found that on Opera 11.50 the expression

 JSON.stringify(2)

returns an object for which

  • typeof returns "string"
  • constructor.name is String
  • charCodeAt(0) is 50
  • length is 1

But still

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

shows "false" in Opera (and the same happens using ===).

Is this a bug or what?

The only way I found to make it compare equal to "2" is calling .substr(0) (for example even adding an empty string still compares different).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

稍尽春風 2024-12-06 12:35:57

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

来自 ECMAScript 5.1 规范:

JSON.parse 和 JSON.stringify 的一致实现必须支持本规范中描述的确切交换格式,而无需对该格式进行任何删除或扩展。这与 RFC 4627 不同,RFC 4627 允许 JSON 解析器接受非 JSON 表单和扩展。

和:

JSON.stringify 生成符合以下 JSON 语法的字符串。 JSON.parse 接受符合 JSON 语法的 String

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

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

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

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

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

That definitely looks like a bug.

From the ECMAScript 5.1 specification:

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.

And:

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

It may be that it somehow wraps the string in a "JSONText" type object which still has a typeof of string but that seems very odd.

I would definitely think that the following implementation in this case is the correct one:

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

According to @6502 (see comment) this is true in:
Chrome; Firefox; IE9; iPad Safari; OsX Safari; the N1 Android browser

The ECMAScript 5.1 specification document: http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文