JavaScript比较中应使用哪个等号运算符? == vs ===

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/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值