简体   繁体   English

如何对 Javascript 中的字符串进行真实身份相等性检查

[英]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.我看过很多关于身份相等运算符===的解释,但似乎它们并不像我们在其他语言(例如 Java)中对身份相等的理解那样准确。

Seems for base types (such as number, string), === return true indicates if two variables are with the same type and value.似乎对于基本类型(例如数字、字符串), === return true 表示两个变量是否具有相同的类型和值。 But not necessarily the same identity (references to the same object).但不一定相同的身份(对同一对象的引用)。 But for array and map, it does.但对于阵列和 map,它确实如此。 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. Javascript 中的字符串是否也有真正的身份相等性检查。 ie s1 === s2 should return false in the above example?s1 === s2在上面的例子中应该返回false吗?

Thanks for the answers.感谢您的回答。 I think the source of the truth is the Javascript language spec regarding Strict Equality Comparison .我认为真相的来源是关于Strict Equality Comparison的 Javascript 语言规范。 It clearly specifies the behavior in SameValueNonNumber(x, y) .它清楚地指定了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.令人困惑的是,许多文章误用了Identity Equality一词而不是Strict Equality ,基于规范没有这样的Identity Equality概念。 (Although it's similar behavior for Object types as specified in item 8 in the SameValueNonNumber(x, y) ). (尽管 Object 类型的行为与SameValueNonNumber(x, y)中第 8 项中指定的类似)。 So I believe the answer is not possible to do a string identity equality check in Javascript.所以我相信答案是不可能在 Javascript 中进行字符串身份相等检查。

This is because a string is a primitive type where an array is an object type.这是因为字符串是原始类型,其中数组是 object 类型。 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 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如果你不确定你在处理什么(一个像numberstring这样的原始数据,或者一个object ), typeof可以弄清楚

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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