如何在 JavaScript 中检查未定义或空变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2559318/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:55:20  来源:igfitidea点击:

How to check for an undefined or null variable in JavaScript?

javascriptnullundefined

提问by Tomas Vana

We are frequently using the following code pattern in our JavaScript code

我们经常在 JavaScript 代码中使用以下代码模式

if (typeof(some_variable) != 'undefined' && some_variable != null)
{
    // Do something with some_variable
}

Is there a less verbose way of checking that has the same effect?

是否有一种不那么冗长的检查方法具有相同的效果?

According to some forums and literature saying simply the following should have the same effect.

根据一些论坛和文献的说法,简单地说以下应该具有相同的效果。

if (some_variable)
{
    // Do something with some_variable
}

Unfortunately, Firebugevaluates such a statement as error on runtime when some_variableis undefined, whereas the first one is just fine for it. Is this only an (unwanted) behavior of Firebug or is there really some difference between those two ways?

不幸的是,当未定义时,Firebug在运行时some_variable将这样的语句评估为错误,而第一个就可以了。这只是 Firebug 的(不需要的)行为还是这两种方式之间真的有一些区别?

采纳答案by user187291

You have to differentiate between cases:

您必须区分情况:

  1. Variables can be undefinedor undeclared. You'll get an error if you access an undeclared variable in any context other than typeof.
  1. 变量可以是undefined或未声明的。如果您在除typeof.
if(typeof someUndeclaredVar == whatever) // works
if(someUndeclaredVar) // throws error

A variable that has been declared but not initialized is undefined.

已声明但未初始化的变量是undefined.

let foo;
if (foo) //evaluates to false because foo === undefined
  1. Undefined properties, like someExistingObj.someUndefProperty. An undefined property doesn't yield an error and simply returns undefined, which, when converted to a boolean, evaluates to false. So, if you don't care about 0and false, using if(obj.undefProp)is ok. There's a common idiom based on this fact:

    value = obj.prop || defaultValue
    

    which means "if objhas the property prop, assign it to value, otherwise assign the default value defautValue".

    Some people consider this behavior confusing, arguing that it leads to hard-to-find errors and recommend using the inoperator instead

    value = ('prop' in obj) ? obj.prop : defaultValue
    
  1. 未定义的属性,例如someExistingObj.someUndefProperty. 未定义的属性不会产生错误,只会返回undefined,当转换为布尔值时,其计算结果为false。所以,如果你不关心 0false,使用if(obj.undefProp)是可以的。有一个基于这个事实的常见习语:

    value = obj.prop || defaultValue
    

    这意味着“如果obj有属性prop,则将其分配给value,否则分配默认值defautValue”。

    有些人认为这种行为令人困惑,认为它会导致难以发现的错误,并建议改用in运算符

    value = ('prop' in obj) ? obj.prop : defaultValue
    

回答by mar10

I think the most efficient way to test for "value is nullor undefined" is

我认为测试“值是nullundefined”的最有效方法是

if ( some_variable == null ){
  // some_variable is either null or undefined
}

So these two lines are equivalent:

所以这两行是等价的:

if ( typeof(some_variable) !== "undefined" && some_variable !== null ) {}
if ( some_variable != null ) {}

Note 1

注 1

As mentioned in the question, the short variant requires that some_variablehas been declared, otherwise a ReferenceError will be thrown. However in many use cases you can assume that this is safe:

正如问题中提到的,short 变体需要some_variable已声明,否则将引发 ReferenceError。但是,在许多用例中,您可以假设这是安全的:

check for optional arguments:

检查可选参数:

function(foo){
    if( foo == null ) {...}

check for properties on an existing object

检查现有对象的属性

if(my_obj.foo == null) {...}

On the other hand typeofcan deal with undeclared global variables (simply returns undefined). Yet these cases should be reduced to a minimum for good reasons, as Alsciende explained.

另一方面typeof可以处理未声明的全局变量(简单地返回undefined)。然而,正如 Alsciende 解释的那样,出于充分的理由,这些情况应该减少到最低限度。

Note 2

笔记2

This - even shorter - variant is notequivalent:

这 - 甚至更短 - 变体是等价的:

if ( !some_variable ) {
  // some_variable is either null, undefined, 0, NaN, false, or an empty string
}

so

所以

if ( some_variable ) {
  // we don't get here if some_variable is null, undefined, 0, NaN, false, or ""
}

Note 3

注 3

In general it is recommended to use ===instead of ==. The proposed solution is an exception to this rule. The JSHint syntax checkereven provides the eqnulloption for this reason.

一般来说,建议使用===代替==。建议的解决方案是此规则的一个例外。该JSHint语法检查器甚至提供eqnull这个原因选项。

From the jQuery style guide:

来自jQuery 风格指南

Strict equality checks (===) should be used in favor of ==. The only exception is when checking for undefined and null by way of null.

// Check for both undefined and null values, for some important reason. 
undefOrNull == null;

应该使用严格的相等检查 (===) 来支持 ==。唯一的例外是通过 null 检查 undefined 和 null 时。

// Check for both undefined and null values, for some important reason. 
undefOrNull == null;

回答by Semra

Checking null with normal equality will also return true for undefined.

使用正常的相等性检查 null 也将为 undefined 返回 true。

if (window.variable == null) alert('variable is null or undefined');

if (window.variable == null) alert('variable is null or undefined');

JS Equality

JS 平等

回答by Naren Yellavula

In newer JavaScript standards like ES5 and ES6 you can just say

在 ES5 和 ES6 等较新的 JavaScript 标准中,你可以说

> Boolean(0) //false
> Boolean(null)  //false
> Boolean(undefined) //false

all return false, which is similar to Python's check of empty variables. So if you want to write conditional logic around a variable, just say

all 返回false,这类似于Python 对空变量的检查。因此,如果您想围绕变量编写条件逻辑,只需说

if (Boolean(myvar)){
   // Do something
}

here "null" or "empty string" or "undefined" will be handled efficiently.

这里“null”或“空字符串”或“未定义”将被有效处理。

回答by Andy E

If you try and reference an undeclared variable, an error will be thrown in all JavaScript implementations.

如果您尝试引用未声明的变量,则所有 JavaScript 实现都会抛出错误。

Properties of objects aren't subject to the same conditions. If an object property hasn't been defined, an error won't be thrown if you try and access it. So in this situation you could shorten:

对象的属性不受相同条件的约束。如果尚未定义对象属性,则在尝试访问它时不会抛出错误。所以在这种情况下,你可以缩短:

 if (typeof(myObj.some_property) != "undefined" && myObj.some_property != null)

to

if (myObj.some_property != null)

With this in mind, and the fact that global variables are accessible as properties of the global object (windowin the case of a browser), you can use the following for global variables:

考虑到这一点,以及全局变量可以作为全局对象的属性访问的事实(window在浏览器的情况下),您可以对全局变量使用以下内容:

if (window.some_variable != null) {
    // Do something with some_variable
}

In local scopes, it always useful to make sure variables are declared at the top of your code block, this will save on recurring uses of typeof.

在局部作用域中,确保在代码块的顶部声明变量总是有用的,这将节省重复使用typeof.

回答by Drew Noakes

Firstly you have to be very clear about what you test. JavaScript has all sorts of implicit conversions to trip you up, and two different types of equality comparator: ==and ===.

首先,您必须非常清楚您要测试的内容。JavaScript 有各种各样的隐式转换来让你失望,还有两种不同类型的相等比较器:=====.

A function, test(val)that tests for nullor undefinedshould have the following characteristics:

test(val)测试nullundefined应具有以下特征的函数:

 test(null)         => true
 test(undefined)    => true
 test(0)            => false
 test(1)            => false
 test(true)         => false
 test(false)        => false
 test('s')          => false
 test([])           => false

Let's see which of the ideas here actually pass our test.

让我们看看这里的哪些想法实际上通过了我们的测试。

These work:

这些工作:

val == null
val === null || val === undefined
typeof(val) == 'undefined' || val == null
typeof(val) === 'undefined' || val === null

These do not work:

这些不起作用:

typeof(val) === 'undefined'
!!val

I created a jsperf entry to compare the correctness and performanceof these approaches. Results are inconclusive for the time being as there haven't been enough runs across different browsers/platforms. Please take a minute to run the test on your computer!

我创建了一个jsperf 条目来比较这些方法的正确性和性能。结果暂时没有定论,因为在不同的浏览器/平台上运行不够。请花一点时间在您的计算机上运行测试!

At present, it seems that the simple val == nulltest gives the best performance. It's also pretty much the shortest. The test may be negated to val != nullif you want the complement.

目前,似乎简单的val == null测试给出了最好的性能。它也几乎是最短的。val != null如果您想要补码,则测试可能会被否定。

回答by Yukulélé

this is the only case in which ==should be used:

这是唯一==应该使用的情况:

if (val == null) console.log('val is null or undefined')

回答by TMS

Since there is no single complete and correct answer, I will try to summarize:

由于没有一个完整且正确的答案,我将尝试总结:

In general, the expression:

一般来说,表达式:

if (typeof(variable) != "undefined" && variable != null)

cannot be simplified, because the variablemight be undeclared so omitting the typeof(variable) != "undefined"would result in ReferenceError. But, you can simplify the expression according to the context:

不能简化,因为variable可能未声明,因此省略typeof(variable) != "undefined"将导致 ReferenceError。但是,您可以根据上下文简化表达式

If the variableis global, you can simplify to:

如果variableglobal,则可以简化为:

if (window.variable != null)

If it is local, you can probably avoid situations when this variable is undeclared, and also simplify to:

如果它是local,您可能可以避免未声明此变量的情况,并且还可以简化为:

if (variable != null)

If it is object property, you don't have to worry about ReferenceError:

如果是对象属性,则不必担心 ReferenceError:

if (obj.property != null)

回答by DDave

You can just check if the variable has a value or not. Meaning,

您可以只检查变量是否有值。意义,

if( myVariable ) {
//mayVariable is not :
//null
//undefined
//NaN
//empty string ("")
//0
//false

}

If you do not know whether a variable exists (that means, if it was declared) you should check with the typeof operator. e.g.

如果你不知道一个变量是否存在(也就是说,如果它被声明了)你应该用 typeof 操作符检查。例如

if( typeof myVariable !== 'undefined' ) {
    // myVariable will get resolved and it is defined
}

回答by Mab Kiani

I have done this using this method

我已经使用这种方法完成了这项工作

save the id in some variable

将 id 保存在某个变量中

var someVariable = document.getElementById("someId");

then use if condition

然后使用 if 条件

if(someVariable === ""){
 //logic
} else if(someVariable !== ""){
 //logic
}