JavaScript比较运算符:Identity与Equality

问题描述:

我一直在努力理解JavaScript的比较运算符之间的区别:身份和平等。根据我的阅读,如果使用==检查两个对象的相等性,JavaScript将尝试确定它们是否是相同类型,如果不是,则尝试将它们设置为相同类型。但是,===的行为方式不同。举个例子:

I've been trying to understand the difference between JavaScript's comparison operators: identity and equality. From what I've read, if you check the equality of two objects using ==, JavaScript will try to figure out if they are the same type and, if not, try to get them to that same type. However, === doesn't behave in the same manner. So as an example:

var n = "1";
console.log(n==1);        // outputs true
console.log(n===1);       // outputs false

那么这些身份运算符和常规相等运算符之间有什么区别?两者兼有的好处是什么?

So what is the difference between these "identity" operators and the regular equality operators? What is the benefit of having both?

性能有差异吗?我认为身份运算符会更快,因为它不会进行转换。

Are there differences in performance? I would think that the identity operator would be faster since it doesn't do conversion.

另外,当涉及更复杂的对象(如数组)时,它们有何不同?最重要的是,惯例会说什么时候应该使用另一个,为什么?

Also, how do these differ when it comes to more complex objects, like arrays? Most importantly, what do conventions say about when one should be used over the other, why?

等于运算符将尝试在进行比较之前使数据类型相同。另一方面,身份运算符要求两种数据类型都与先决条件相同。

The equality operator will attempt to make the data types the same before making the comparison. On the other hand, the identity operator requires both data types to be the same as a prerequisite.

还有很多其他帖子与此问题相似。请参阅:

There are quite a few other posts out there similar to this questions. See:

PHP等式(==双等于)和身份(===三等于)比较运算符有何不同?(有一个很好的比较图表)

哪个等于运算符(== vs ===)应该用于JavaScript比较?

How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ? (has a nice comparison chart)
Which equals operator (== vs ===) should be used in JavaScript comparisons?

实际上,当您想要确定布尔值为true或false时,身份运算符非常方便...

In practice, the identity operator comes in really handy when you want to be certain that a boolean value is true or false since...

1 == true     => true
true == true  => true
1 === true    => false
true === true => true