简体   繁体   中英

How to do real identity equality check for string in Javascript

I have seen many explanations of identity equal operator === , but seems they are not quite accurate as what we understand of identity equality in other languages such as Java.

Seems for base types (such as number, string), === return true indicates if two variables are with the same type and value. But not necessarily the same identity (references to the same object). But for array and map, it does. Here are some examples that cause confusion for me:

 s1 = 'a' + '1' s2 = 'a' + '1' s1 === s2 // true, even they actually reference two different objects in memory which suppose to be different identities. a1 = [1,2] a2 = [1,2] a1 === a2 // false, as they reference two different objects in memory, even their values are the same.

Could somebody confirm my understanding is right? Also is there a real identity equality check for strings in Javascript. ie s1 === s2 should return false in the above example?

Thanks for the answers. I think the source of the truth is the Javascript language spec regarding Strict Equality Comparison . It clearly specifies the behavior in SameValueNonNumber(x, y) . The confusion is many articles misused the term Identity Equality instead of Strict Equality , there's no such concept of Identity Equality based on the spec. (Although it's similar behavior for Object types as specified in item 8 in the SameValueNonNumber(x, y) ). So I believe the answer is not possible to do a string identity equality check in Javascript.

This is because a string is a primitive type where an array is an object type. Primitives can be compared as you'd expect however when comparing objects, you're comparing the references and not the objects themselves.

s1 = new String('a1');
s2 = new String('a1');
s1 === s2 // false

Equality comparisons and sameness over on MDN

If you are uncertain about what you are dealing with (a primitive like number or string , or an object ), typeof is there to figure out

typeof new String() // object
typeof '' // string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM