In JavaScript you can use two different operators to check for object equality. They are ==
and ===
.
在JavaScript中,您可以使用两个不同的运算符来检查对象是否相等。 它们是==
和===
。
They basically do the same thing, but there is a big difference between the two.
他们基本上做相同的事情,但是两者之间有很大的不同。
===
will check for equality of two values. If they are objects, the objects must be of the same type. JavaScript is not typed, as you know, but you have some fundamental types which you must know about.
===
将检查两个值是否相等。 如果它们是对象,则这些对象必须具有相同的类型。 如您所知,没有键入JavaScript,但是您必须了解一些基本类型。
In particular we have value types (Boolean, null, undefined, String and Number) and reference types (Array, Object, Function).
特别是,我们有值类型(布尔,空,未定义,字符串和数字)和引用类型(数组,对象,函数)。
If two values are not of the same type, ===
will return false.
如果两个值的类型不同,则===
将返回false。
If they are of the same type, JavaScript will check for equality.
如果它们是同一类型,JavaScript将检查是否相等。
With reference types, this means the values need to reference the same object / array / function. Not one with the same values: the same one.
对于引用类型 ,这意味着值需要引用相同的对象/数组/函数。 没有一个具有相同的值:相同的一个。
==
is different because it will attempt to convert types to match.
==
是不同的,因为它将尝试将类型转换为匹配。
This is why you get results like
这就是为什么你得到像
false == '0' //true
false === '0' //false
null == undefined //true
null === undefined //false
In my experience, in 97% of the cases you’ll want to use ===
, unless ==
provides exactly what you want. It has less drawbacks and edge cases.
以我的经验,在97%的情况下,除非==
完全提供您想要的内容,否则您将使用===
。 它具有较少的缺点和边缘情况。
The same goes for !=
and !==
, which perform the same thing, but negated.
!=
和!==
也是一样,它们执行相同的操作,但取反。
Always default to !==
.
始终默认为!==
。
翻译自: https://flaviocopes.com/javascript-comparison-operator-difference/