JavaScript:如何测试一个变量是否不为NULL [英] JavaScript: how to test if a variable is not NULL
本文介绍了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
是除了<$ c之外的任何值,则第二个将执行该块( true $ 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
这篇关于JavaScript:如何测试一个变量是否不为NULL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文