问题描述
当我将undefined和null与Boolean false进行比较时,该语句返回false:
When I compare undefined and null against Boolean false, the statement returns false:
undefined == false;
null == false;
返回false。为什么?
It return false. Why?
推荐答案
原始答案指向要删除的规范,我想提供一个链接和简短的摘录这里的规范。
With the original answer pointing to the spec being deleted, I'd like to provide a link and short excerpt from the spec here.
ECMA spec doc列出 undefined == false
返回false的原因。虽然它没有直接说明为什么会这样,但回答这个问题最重要的部分在于这句话:
The ECMA spec doc lists the reason that undefined == false
returns false. Although it does not directly say why this is so, the most important part in answering this question lies in this sentence:
The comparison x == y, where x and y are values, produces true or false.
如果我们查找null的定义,我们会发现如下:
If we look up the definition for null, we find something like this:
NULL or nil means "no value" or "not applicable".
在Javascript中, undefined
的处理方式相同。它没有任何价值。但是,false确实有价值。它告诉我们事情并非如此。而 undefined
和 null
不应该给我们任何价值。同样,它没有什么可以转换为它的抽象相等比较,因此结果总是错误的。这也是为什么 null == undefined
返回true(它们都没有任何值)。应该注意的是, null === undefined
因为它们的类型不同而返回false。 (在控制台中使用 typeof(null)
和 typeof(未定义)
来检查它)
In Javascript, undefined
is treated the same way. It is without any value. However, false does have a value. It is telling us that something is not so. Whereas undefined
and null
are not supposed to be giving any value to us. Likewise, there is nothing it can convert to for its abstract equality comparison therefore the result would always be false. It is also why null == undefined
returns true (They are both without any value). It should be noted though that null === undefined
returns false because of their different types. (Use typeof(null)
and typeof(undefined)
in a console to check it out)
但我很好奇的是,将 NaN
与任何事物进行比较总是返回false 。即使将它与自身进行比较。 [ NaN == NaN
返回false]
What I'm curious of though, is that comparing NaN
with anything at all will always return false. Even when comparing it to itself. [NaN == NaN
returns false]
另外,另一条奇怪的信息:[ typeof NaN
返回数字]
Also, another odd piece of information: [typeof NaN
returns "number"]
如果可能,应避免使用==运算符来比较两个值。而是使用===来真正看出两个值是否相等。 ==给出一种错觉,即当两个值可能不是通过使用强制时,它们确实完全相同。示例:
If possible, you should avoid using the == operator to compare two values. Instead use === to truly see if two values are equal to each other. == gives the illusion that two values really are exactly equal when they may not be by using coercion. Examples:
5 ==5
为真
5 ===5
为假
== false
为真
=== false
为假
0 == false
为真
0 === false
为假
这篇关于为什么“undefined等于false”归还假吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!