您的位置:首页 > Web前端 > JavaScript

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

2017-05-11 15:12 459 查看
转载自:
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
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

常见的几种比较:
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  文章 undefined false