Benjamin - 专注前端开发和用户体验

Javascript中使用Object.is()判断严格相等

点滴Javascript Benjamin 2084℃ 0评论

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

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

console.log(NaN == NaN); //false
console.log(Object.is(NaN, NaN)); //true

console.log(+0 == -0);  //true
console.log(+0 === -0); //true
console.log(Object.is(+0, -0)); //false

具体有以下几种情况:

  • both undefined
  • both null
  • both true or 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

常见的几种比较:

x y == === 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
0 0 true true true
+0 -0 true true false
0 false true false false
"" false true false false
"" 0 true false false
"0" 0 true false false
"17" 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
0 null false false false
0 NaN false false false
"foo" NaN false false false
NaN NaN false false true

NOTE: Type(undefined) is Undefined, Type(null) is Null, and Type(false) is Boolean
undefined == false is equivalent to undefined == 0 (line 7), which is false (line 10)
null == false is equivalent to null == 0 (line 7) which is also false (line 10)
Note that, due to the carveout in lines 2-3, undefined == null is true

关于上述结果产生的原因可以参考:The Abstract Equality Comparison Algorithm

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

喜欢 (1)
发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址