JavaScript:如何测试一个变量是否不为NULL
问题描述:
我的理解是下面的两行JavaScript是等价的,但我很困惑这是最好的做法使用:
My understanding is the two JavaScript lines below are equivalent but I'm confused which is the best practice to use:
我应该:
if (myVar) {...}
或
if (myVar !== null) {...}
答
如果 myVar
是 truthy ,则第一个将执行 if
如果 myVar
是除了 true $ c> $ c> null 。
They are not equivalent. The first will execute the block following the if
statement if myVar
is truthy (i.e. evaluates to true
in a conditional), while the second will execute the block if myVar
is any value other than null
.
JavaScript中唯一不真实的值是以下(aka falsy ):
The only values that are not truthy in JavaScript are the following (a.k.a. falsy values):
-
null
- code> undefined
-
0
- code>(空字符串)
-
false
-
NaN
null
undefined
0
-
""
(the empty string) false
NaN