在JavaScript中测试null和undefined的更短方法? [英] Shorter way of testing for null and undefined in JavaScript?

查看:105
本文介绍了在JavaScript中测试null和undefined的更短方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在读一本书,上面写着虽然可以测试一个变量是否已定义并且具有以下值:

I'm reading a book that says that while it's possible to test whether a variable is defined and has a value by doing:

if(myVar != null && myVar != undefined) {
  ...
}

这被认为是糟糕的风格,而且因为 null 未定义是假值,我们可以通过使用更简洁的来更容易地检查变量是否具有值构造

this is considered “poor style”, and that since both null and undefined are falsey values, we can more easily check if a variable has a value by using the more concise if construct

if(myVar) {
  ...
}

但这让我感到困惑,因为虽然 null undefined 是假的值,它们不是唯一的假值。换句话说,在我看来,前 if 语句说,只要变量不为null或未定义,就运行代码,而后者 if 语句说只要变量不是假的就运行代码。假设 myVar == 0 ,那么前 if 语句会运行,但后者 if 语句不会。因此这两个如果语句不相同。我错了吗?

But this confuses me, because while it’s true that null and undefined are falsey values, they are not the only falsey values. In other words, it seems to me that the former if statement says, "run the code as long as the variable isn't null or undefined, whereas the latter if statement is saying, "run the code as long as the variable isn't falsey." Supposing myVar == 0, then the former if statement would run, but the latter if statement would not. Therefore these two if statements are not equivalent. Am I wrong?

编辑:如果你想看到他们的确切措辞,这是一个屏幕抓取:

Here's a screen grab if you want to see their exact wording:

推荐答案

检查变量是否为 null undefined ,使用非单一等于运算符检查 null

To check if the variable is either null or undefined, use the not single equal operator checking for null.

if (myVar != null) {

}

但是,最好使用三等于更明确。

However, it's always best practice to use triple equals to be more explicit.

if (!(myVar === null || typeof myVar === 'undefined')) {

}

比较

(undefined == null) => true
(null == null) => true
(undefined === null) => false
(null === null) => true
(0 == null) => false
(0 == undefined) => false
(0 === null) => false
(0 === undefined) => false
(false == null) => false
(false == undefined) => false
(false === null) => false
(false === undefined) => false
(null) => false
(undefined) => false
(0) => false
(false) => false

DEMO: http://jsfiddle.net/xk9L3yuz/3/

DEMO: http://jsfiddle.net/xk9L3yuz/3/

这篇关于在JavaScript中测试null和undefined的更短方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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