Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

javascript - Object.is vs ===

I stumbled upon a code example which was using this comparison:

var someVar = 0;
Object.is(false, someVar); //Returns false 

I know false == 0 will be true that's why we have ===.

How is Object.is different from ===?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

=== is called strict comparison operator in JavaScript. Object.is and strict comparison operator behave exactly the same except for NaN and +0/-0.

From MDN:

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 treats Number.NaN as not equal to NaN.

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

enter image description here

You can find more examples here.

Note: Object.is is part of the ECMAScript 6 proposal and is not widely supported yet (e.g. it's not supported by any version of Internet Explorer or many older versions of other browsers). However you can use a polyfill for non-ES6 browsers which can be found in link given above.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...