四种相等算法
-
==
类型转换 +0==-0
NaN!=NaN
-
===
不转类型,+0===-0
NaN!==NaN
used by Array.prototype.indexOf
, Array.prototype.lastIndexOf
case-matching
是啥😳
-
SameValueZero
used by Map
and Set
Array.prototype.includes
[NaN].includes(NaN)
[+0].includes(-0)
mdn上还有String.prototype.includes
但是这个会先对参数先转string
还有些不常用的
-
SameValue
: used in all other places 值相等 Object.is
type |
+0 -0 |
NaN |
== |
等 |
不等 |
=== |
等 |
不等 |
SameValueZero |
等 |
等 |
SameValue |
不等 |
等 |
js提供的 三种判断
-
===
Strict Equality
-
==
Abstract Equality
-
Object.is
SameValue ES2015新增(es6)
var a = {valueOf(){return 1}}
var b = {valueOf(){return 1}}
var c = {toString(){return '1'}}
var d = {toString(){return '1'}}
console.log(a == 1)
console.log(a == '1')
console.log(b == 1)
console.log('a == b' ,a == b) // false
console.log('c == d' ,c == d) // false
// === 判断类型、NaN不等NaN (The only case in which (x !== x) is true is when x is NaN)
// Object.is 其他和===类似 但是 NaN等NaN +0不等-O
// Object.is ES2015新增
console.log('NaN == NaN', NaN == NaN) // false
console.log('NaN === NaN', NaN === NaN) // false
console.log(Object.is(NaN, NaN))
console.log(+0 === -0)
console.log('Object.is(+0, -0)', Object.is(+0, -0)) // false