转载自:

http://www.tuicool.com/articles/eiAfMvV


http://www.zuojj.com/archives/1211.html?utm_source=tuicool&utm_medium=referral


在Javascript中判断相等是很常见的,常用的判断有“==”,“===”,“!=”,“!==”,今天这篇文章我们来学习ES6中的一个方法Object.is(),关于此方法的详细介绍可以戳    这里。

Object.is()方法用来判断两个值是否有相同的值,这个相同的值的判定和“==”,“===”的判断不同,比如:

console.log(NaN == NaN); //falseconsole.log(Object.is(NaN, NaN)); //trueconsole.log(+0 == -0);  //trueconsole.log(+0 === -0); //trueconsole.log(Object.is(+0, -0)); //false  

具体有以下几种情况:

  • both              undefined      

  • both              null      

  • both      trueor both      false

  • both strings of the same length with the same characters

  • both the same object

  • both numbers and

    • both          +0

    • both          -0

    • both                      NaN          

    • or both non-zero and both not                      NaN          and both have the same value

常见的几种比较:

Sameness Comparisons
xy==        ===        Object.is        
undefined        undefined        true        true        true        
null        null        true        true        true        
true        true        true        true        true        
false        false        true        true        true        
"foo"        "foo"        true        true        true        
{ foo: "bar" }        x        true        true        true        


true        true        true        
+0        -0        true        true        false        

false        true        false        false        
""        false        true        false        false        
""        
true        false        false        
"0"        
true        false        false        
"17"        
true        false        false        
[1,2]        "1,2"        true        false        false        
new String("foo")        "foo"        true        false        false        
null        undefined        true        false        false        
null        false        false        false        false        
undefined        false        false        false        false        
{ foo: "bar" }        { foo: "bar" }        false        false        false        
new String("foo")        new String("foo")        false        false        false        

null        false        false        false        

NaN        false        false        false        
"foo"        NaN        false        false        false        
NaN        NaN        false        false        true        

因为Object.is()是ES6规范草案的一部分,现在只有Chrome/FF的部分版本支持,如果你想兼容其它浏览器及低版本,可以使用Polyfill或者    ES6-shim。