JavaScript:`if(!x)`和`if(x == null)`有什么区别? [英] JavaScript: What is the difference between `if (!x)` and `if (x == null)`?
问题描述
if(!x)
和 if(x == null)
之间的区别是什么?也就是说,他们的结果什么时候可以不同?
!x
将为每个falsy值返回 true
(空字符串, 0
, null
, false
, undefined
, NaN
)而 x == null
只返回 true
如果 x
null
(编辑:或显然未定义
(见下文))。
尝试 x = 0
,有区别。
您可以说NOT运算符!
将值转换为其相反的布尔值。这与实际比较两个值不同。
此外,如果您将值与 需要阅读的内容: 更新: 有关<$ c $的非严格比较的详细信息c> null == $进行比较c $ c>,JavaScript会 类型转换 ,这会导致意外行为(如
和 undefined == null
)。最好总是使用严格比较 ===
(值和类型必须相同)并且只有在你真正知道自己在做什么时才使用类型转换。 / p>
undefined
(或一般的比较),值得一看 规范 。比较算法在那里定义(比较是 x == y
):
- 如果Type( x )与Type( y )相同,那么
(...)
- 如果 x null 且 y 未定义,则返回真即可。
- 如果 x 未定义且 y null ,则返回 true 。
- (...)
(.. 。)
What is the difference between if (!x)
and if (x == null)
; that is, when can their results be different?
!x
will return true
for every "falsy" value (empty string, 0
, null
, false
, undefined
, NaN
) whereas x == null
will only return true
if x
is null
(edit: or apparently undefined
(see below)).
Try with x = 0
, there is a difference.
You can say that the NOT operator !
converts a value into its opposite boolean equivalent. This is different than actually comparing two values.
In addition, if you compare values with ==
, JavaScript does type conversion which can lead to unexpected behavior (like undefined == null
). It is better to always use strict comparison ===
(value and type must be the same) and make use of type conversion only if you really know what you are doing.
Something to read:
Update:
For more information about the non-strict comparison of null
and undefined
(or the comparison in general), it is worth having a look at the specification. The comparison algorithm is defined there (the comparison is x == y
):
- If Type(x) is the same as Type(y), then
(...)- If x is null and y is undefined, return true.
- If x is undefined and y is null, return true.
- (...)
(...)
这篇关于JavaScript:`if(!x)`和`if(x == null)`有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!