Object.is vs === [英] Object.is vs ===
问题描述
我偶然发现了使用这种比较的代码示例:
I stumbled upon a code example which was using this comparison:
var someVar = 0;
Object.is(false, someVar); //Returns false
我知道 false == 0
将是 true
这就是为什么我们有 ===
。
I know false == 0
will be true
that's why we have ===
.
与 ===
不同, Object.is
如何?
推荐答案
===
在JavaScript中称为严格比较运算符。 Object.is
和严格比较运算符的行为完全相同,除了 NaN
和 + 0 / -0
。
===
is called strict comparison operator in JavaScript. Object.is
and strict comparison operator behave exactly the same except for NaN
and +0/-0
.
从MDN:
Object.is()
方法与根据===
运算符相等而不相同。将===
运算符(以及==
运算符)将数值-0和+0作为等于和Number.NaN
不等于NaN
。
Object.is()
method is not the same as being equal according to the===
operator. The===
operator (and the==
operator as well) treats the number values -0 and +0 as equal and treatsNumber.NaN
as not equal toNaN
.
下面的代码突出显示了 ===
和 Object.is()$ c $之间的区别c>。
Code below highlights the difference between ===
and Object.is()
.
console.log(+0 === -0); //true
console.log(Object.is(+0, -0)); //false
console.log(NaN === NaN); // false
console.log(Object.is(NaN, NaN)); //true
console.log(Number.NaN === Number.NaN); // false
console.log(Object.is(Number.NaN, Number.NaN)); // true
console.log(NaN === Number.NaN); // false
console.log(Object.is(NaN, Number.NaN)); // true
您可以找到更多示例这里。
You can find more examples here.
注意: Object.is
是ECMAScript 6提案的一部分,不广泛支持了但是,您可以使用polyfill进行非ES6浏览器,可在上述链接中找到。
Note: Object.is
is part of the ECMAScript 6 proposal and not widely supported yet. However you can use polyfill for non-ES6 browsers which can be found in link given above.
这篇关于Object.is vs ===的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!