最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is it correct that JSON.stringify(2) == "2" may return false? - Stack Overflow

programmeradmin0浏览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 pare equal to "2" is calling .substr(0) (for example even adding an empty string still pares different).

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 pare equal to "2" is calling .substr(0) (for example even adding an empty string still pares different).

Share Improve this question edited Aug 14, 2011 at 17:41 6502 asked Aug 14, 2011 at 16:39 65026502 115k16 gold badges175 silver badges275 bronze badges 16
  • 4 If it is so then it is a bug. Minimalistic sample to try would be helpful to say for sure. – c-smile Commented Aug 14, 2011 at 16:42
  • 3 Interesting, == 2 yields true... – Tomasz Nurkiewicz Commented Aug 14, 2011 at 16:44
  • 4 Does it also return false if you use x === "2" ? – Tom Commented Aug 14, 2011 at 16:48
  • 2 Another interesting thing is that the bug occurs with and only with numbers 0 to 9. – duri Commented Aug 14, 2011 at 17:05
  • 2 How interesting, that I'm not suprised. Opera is crazy! – KARASZI István Commented Aug 14, 2011 at 17:06
 |  Show 11 more ments

1 Answer 1

Reset to default 7

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 ment) 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/publications/files/ECMA-ST/Ecma-262.pdf

发布评论

评论列表(0)

  1. 暂无评论