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?
此外,当涉及到更复杂的对象(如数组)时,它们有何不同?最重要的是,关于什么时候应该使用其中一个,为什么呢?
4 个解决方案
#1
19
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比较中,是否应该使用与操作符=== == ?
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
#2
13
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不相同,因此结果为false。
Reference is here:
https://developer.mozilla.org/en/JavaScript/Reference/Operators/Comparison_Operators
参考这里:https://developer.mozilla.org/en/JavaScript/Reference/Operators/Comparison_Operators
#3
6
==
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.
如您所见==有很多复杂的类型转换逻辑。正因为如此,很难预测你会得到什么结果——这可能会导致bug。
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**
#4
1
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.
原因是identity或strict运算符(=== =)与无类型转换进行比较,这意味着如果两个值都没有相同的值和相同的类型,那么它们就不会被认为是相等的。
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身份- vs -平等-战争- - - vs - 758 d396e922 # .hhg396ey9理解
#1
19
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比较中,是否应该使用与操作符=== == ?
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
#2
13
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不相同,因此结果为false。
Reference is here:
https://developer.mozilla.org/en/JavaScript/Reference/Operators/Comparison_Operators
参考这里:https://developer.mozilla.org/en/JavaScript/Reference/Operators/Comparison_Operators
#3
6
==
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.
如您所见==有很多复杂的类型转换逻辑。正因为如此,很难预测你会得到什么结果——这可能会导致bug。
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**
#4
1
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.
原因是identity或strict运算符(=== =)与无类型转换进行比较,这意味着如果两个值都没有相同的值和相同的类型,那么它们就不会被认为是相等的。
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身份- vs -平等-战争- - - vs - 758 d396e922 # .hhg396ey9理解