JavaScript 比较运算符:身份与平等

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5447024/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:13:57  来源:igfitidea点击:

JavaScript comparison operators: Identity vs. Equality

javascriptoperatorscomparison-operatorsequivalence

提问by Hristo

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:

我一直试图理解 JavaScript 的比较运算符之间的区别:身份和相等。从我读到的内容来看,如果您使用 == 检查两个对象的相等性,JavaScript 将尝试确定它们是否是相同的类型,如果不是,则尝试将它们转换为相同的类型。但是, === 的行为方式不同。举个例子:

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?

此外,当涉及到更复杂的对象(如数组)时,它们有何不同?最重要的是,约定何时应该使用一个而不是另一个,为什么?

回答by Michael Copeland

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:

还有很多其他帖子类似于这个问题。看:

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?

PHP 等式(== 双等式)和恒等式(=== 三等式)比较运算符有何不同?(有一个很好的比较图表)
在 JavaScript 比较中应该使用哪个等于运算符 (== vs ===)?

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

回答by Joel Coehoorn

The difference is that ==, <=, >= and != will do type coercion — for example, force a string to be evaluated as a number. ===, <==, >==, and !== will not do type coercion. They will compare a string to a number, and since the string "1" is not the same as the numeric value 1, the result is false.

不同之处在于 ==、<=、>= 和 != 会进行类型强制——例如,强制将字符串计算为数字。===、<==、>== 和 !== 不会进行类型强制。他们会将字符串与数字进行比较,由于字符串“1”与数值 1 不同,因此结果为假。

Reference is here:
https://developer.mozilla.org/en/JavaScript/Reference/Operators/Comparison_Operators

参考在这里:https:
//developer.mozilla.org/en/JavaScript/Reference/Operators/Comparison_Operators

回答by Luis Perez

==is the same things as ===, except that ==does type conversion

==是一样的东西===,除了==类型转换

To show you what I mean here is a JavaScript function that behaves exactly like ==:

为了向您展示我的意思,这里有一个 JavaScript 函数,其行为完全类似于==

// loseEqual() behaves just like `==`
function loseEqual(x, y) {
    // notice the function only uses "strict" operators 
    // like `===` and `!==` to do comparisons

    if(typeof y === typeof x) return y === x;

    if(typeof y === "function" || typeof x === "function") return false;

    // treat null and undefined the same
    var xIsNothing = (y === undefined) || (y === null);
    var yIsNothing = (x === undefined) || (x === null);

    if(xIsNothing || yIsNothing) return (xIsNothing && yIsNothing);

    if(typeof x === "object") x = toPrimitive(x);
    if(typeof y === "object") y = toPrimitive(y);

    if(typeof y === typeof x) return y === x;

    // convert x and y into numbers if they are not already use the "+" trick
    if(typeof x !== "number") x = +x;
    if(typeof y !== "number") y = +y;

    return x === y;
}

function toPrimitive(obj) {
    var value = obj.valueOf();
    if(obj !== value) return value;
    return obj.toString();
}

This function should help explain why people keep saying you shouldn't use ==.

这个函数应该有助于解释为什么人们一直说你不应该使用==.

As you can see ==has a lot of complicated logic for type conversion. Because of that it's hard to predict what result you are going to get - and that can lead to bugs.

如您所见==,类型转换有很多复杂的逻辑。正因为如此,很难预测你会得到什么结果——这可能会导致错误。

Here are some examples of some results you wouldn't expect:

以下是一些您意想不到的结果示例:

Unexpected Truths

意想不到的真相

[1] == true // returns true
'0' == false // returns true
[] == false // returns true
[[]] == false // returns true
[0] == false // returns true

'\r\n\t' == 0 // returns true

Unexpected Conclusions

意想不到的结论

// IF an empty string '' is equal to the number zero (0)
'' == 0 // return true

// AND the string zero '0' is equal to the number zero (0)
'0' == 0 // return true

// THEN an empty string must be equal to the string zero '0'
'' == '0' // returns **FALSE**

Objects with Special Functions

具有特殊功能的对象

// Below are examples of objects that
// implement `valueOf()` and `toString()`

var objTest = {
    toString: function() {
        return "test";
    }
};

var obj100 = {
    valueOf: function() {
        return 100;
    }
};

var objTest100 = {
    toString: function() {
        return "test";
    },
    valueOf: function() {
        return 100;
    }
};

objTest == "test" // returns true
obj100 == 100 // returns true
objTest100 == 100 // returns true

objTest100 == "test" // returns **FALSE**

回答by ludico8

The reason is that identity or strict operator (===), it compares with no type conversion, that means if both values doesn't have the same value and the same type, they won't be considered equal.

原因是身份或严格运算符(===),它与没有类型转换进行比较,这意味着如果两个值没有相同的值和相同的类型,它们将不被视为相等。

A more clear explanation in the following link:

以下链接中有更清晰的解释:

https://medium.com/@ludico8/identity-vs-equality-battle-of-understanding-vs-758d396e922#.hhg396ey9

https://medium.com/@ludico8/identity-vs-equality-battle-of-understanding-vs-758d396e922#.hhg396ey9