JavaScript等同传递性很奇怪 [英] JavaScript equality transitivity is weird

查看:176
本文介绍了JavaScript等同传递性很奇怪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读 Douglas Crockford的 JavaScript:好的部分 ,我遇到了一个对我来说没有意义的奇怪的例子:

I've been reading Douglas Crockford's JavaScript: The Good Parts, and I came across this weird example that doesn't make sense to me:

'' == '0'           // false
0 == ''             // true
0 == '0'            // true

false == undefined  // false
false == null       // false
null == undefined   // true

作者还提到永远不要使用 == != 。相反,请始终使用 === !== 。但是,他没有解释为什么表现出上述行为?所以我的问题是,为什么上面的结果是这样的? JavaScript中不考虑传递性吗?

The author also goes on to mention "to never use == and !=. Instead, always use === and !==". However, he doesn't explain why the above behavior is exhibited? So my question is, why are the above results as they are? Isn't transitivity considered in JavaScript?

推荐答案

'' == '0' // false

左边是一个空字符串,右边是一个字符串字符。它们是错误的,因为它在两个不相同的字符串之间进行比较(感谢 Niall )。

The left hand side is an empty string, and the right hand side is a string with one character. They are false because it is making a comparison between two un identical strings (thanks Niall).

0 == '' // true

因此,为什么这个是真的,因为 0 falsy 而空字符串是 falsy

Hence, why this one is true, because 0 is falsy and the empty string is falsy.

0 == '0' // true

这个有点棘手。规范声明如果操作数是字符串和数字,则将字符串强制转换为数字。 '0'变为 0 。感谢 smfoote

This one is a bit trickier. The spec states that if the operands are a string and a number, then coerce the string to number. '0' becomes 0. Thanks smfoote.

false == undefined // false

undefined 在JavaScript中很特殊,除了 null 之外不等于其他任何东西。但是,它是 falsy

The value undefined is special in JavaScript and is not equal to anything else except null. However, it is falsy.

false == null // false

同样, null 是特殊的。它只等于 undefined 。它也是 falsy

Again, null is special. It is only equal to undefined. It is also falsy.

null == undefined // true

null undefined 是相似的,但不一样。 null 表示 nothing ,而 undefined 是未设置或不存在的变量的值。将它们的价值视为平等是有道理的。

null and undefined are similar, but not the same. null means nothing, whilst undefined is the value for a variable not set or not existing. It would kind of make sense that their values would be considered equal.

如果你真的很困惑,请检查一下......

If you want to be really confused, check this...

'\n\r\t' == 0

仅包含空格的字符串被视为等于0.

A string consisting only of whitespace is considered equal to 0.

Douglas Crockford提出了很多建议,但你没有把它们当作福音。 :)

Douglas Crockford makes a lot of recommendations, but you don't have to take them as gospel. :)

T.J. Crowder 提出了一个很好的建议,即研究 ECMAScript语言规范了解这些平等测试背后的全部故事。

T.J. Crowder makes an excellent suggestion of studying the ECMAScript Language Specification to know the whole story behind these equality tests.

进一步阅读?

规范

yolpo(关于假值)

这篇关于JavaScript等同传递性很奇怪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆