JavaScript equal operations anomalies

拜拜、爱过 提交于 2019-12-12 15:24:17

问题


I'm working on a lecture about hard to understand JavaScript code and of course on of the weak point of JavaScript is knowing what == / === will return. I found this great answer in stack that covers this subject nicely - Which equals operator (== vs ===) should be used in JavaScript comparisons?

one of the things that caught my eyes (probably because I wasn't aware of it until now) was that you can use String Objects instead of primitives and you will get different result in your conditions -

"abc" == new String("abc")    // true
"abc" === new String("abc")   // false

I wanted to test it and found out a few not so intuitive results using String Objects -

new String("abc") === new String("abc")    // false

and even

new String("abc") == new String("abc")   // false

at the beginning I thought this is a browser bug, but I tested it both on chrome and Firefox. So I'd be really happy if some one could share more information how can it be that comparing a literal string and a string object will be truthy but comparing two "equal" string objects will be falsy


回答1:


comparing two "equal" string objects will be falsy

I've highlighted the important word above. Two object references are never equal to each other unless they refer to exactly the same object.

You're creating two new instances of String. That's two separate objects, even if they do have the same string value.

var s1 = new String("abc"),
    s2 = new String("abc");

s1 === s1; // true
s1 === s2; // false

This is summarised in the spec by the following line in both the abstract equality algorithm and the strict equality algorithm:

Return true if x and y refer to the same object. Otherwise, return false.



来源:https://stackoverflow.com/questions/16149676/javascript-equal-operations-anomalies

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!