如何在 JavaScript 中检查未定义或 null 变量?
我们经常在 JavaScript 代码中使用以下代码模式
if (typeof(some_variable) != 'undefined' && some_variable != null)
{
// Do something with some_variable
}
是否有一种不太冗长的检查方法可以达到相同的效果?
根据一些论坛和文献的说法,简单来说以下应该具有相同的效果。
if (some_variable)
{
// Do something with some_variable
}
不幸的是,Firebug 在 some_variable< 时将此类语句评估为运行时错误/code> 未定义,而第一个就可以了。这只是 Firebug 的(不需要的)行为还是这两种方式之间确实有一些区别?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(29)
我认为测试“value is
null
orundefined
”的最有效方法是所以这两行是等效的:
Note 1
正如中提到的问题是,短变体要求已声明
some_variable
,否则将引发 ReferenceError 。然而,在许多用例中,您可以假设这是安全的:检查可选参数:
检查现有对象的属性
另一方面,
typeof
可以处理未声明的全局变量(简单地返回undefined )。然而,正如阿尔森德所解释的那样,这些案例应该减少到最低限度,这是有充分理由的。
注释 2
这个 - 甚至更短 - 变体不等效:
所以
注释 3
一般来说,建议使用
===< /code> 而不是
==
。所提出的解决方案是该规则的一个例外。为此,JSHint 语法检查器 甚至提供了
eqnull
选项。来自 jQuery 样式指南:
编辑 2021-03:
现在大多数浏览器
支持空值合并运算符 (
??)
和 逻辑 nullish 赋值
(??=)
,它允许更简洁的方式如果变量为 null 或未定义,则分配默认值,例如:
可以写为以下任何形式
I think the most efficient way to test for "value is
null
orundefined
" isSo these two lines are equivalent:
Note 1
As mentioned in the question, the short variant requires that
some_variable
has been declared, otherwise a ReferenceError will be thrown. However in many use cases you can assume that this is safe:check for optional arguments:
check for properties on an existing object
On the other hand
typeof
can deal with undeclared global variables (simply returnsundefined
). Yet these cases should be reduced to a minimum for good reasons, as Alsciende explained.Note 2
This - even shorter - variant is not equivalent:
so
Note 3
In general it is recommended to use
===
instead of==
.The proposed solution is an exception to this rule. The JSHint syntax checker even provides the
eqnull
option for this reason.From the jQuery style guide:
EDIT 2021-03:
Nowadays most browsers
support the Nullish coalescing operator (
??
)and the Logical nullish assignment
(??=)
, which allows a more concise way toassign a default value if a variable is null or undefined, for example:
can be written as any of these forms
您必须区分不同情况:
未定义
或未声明。如果您在typeof
之外的任何上下文中访问未声明的变量,您将会收到错误。已声明但未初始化的变量是
未定义
。未定义的属性,例如
someExistingObj.someUndefProperty
。未定义的属性不会产生错误,只会返回undefined
,当转换为布尔值时,其计算结果为false
。所以,如果你不关心0
和false
,使用if(obj.undefProp)
就可以了。基于这个事实有一个常见的习语:这意味着“如果
obj
具有属性prop
,则将其分配给value
,否则分配默认值defaultValue”。
有些人认为这种行为令人困惑,认为它会导致难以发现的错误,并建议使用
in
运算符代替You have to differentiate between cases:
undefined
or undeclared. You'll get an error if you access an undeclared variable in any context other thantypeof
.A variable that has been declared but not initialized is
undefined
.Undefined properties , like
someExistingObj.someUndefProperty
. An undefined property doesn't yield an error and simply returnsundefined
, which, when converted to a boolean, evaluates tofalse
. So, if you don't care about0
andfalse
, usingif(obj.undefProp)
is ok. There's a common idiom based on this fact:which means "if
obj
has the propertyprop
, assign it tovalue
, otherwise assign the default valuedefautValue
".Some people consider this behavior confusing, arguing that it leads to hard-to-find errors and recommend using the
in
operator instead使用正常相等检查 null 也将针对未定义返回 true。
if (window.variable == null)alert('变量为 null 或未定义');
Checking null with normal equality will also return true for undefined.
if (window.variable == null) alert('variable is null or undefined');
这是唯一应使用
==
和!=
的情况:对于任何其他比较,严格比较器(
===
和应使用!==
)。This is the only case in which
==
and!=
should be used:For any other comparisons, the strict comparators (
===
and!==
) should be used.在像 ES5 和 ES6 这样的新 JavaScript 标准中,你可以直接说
all return false,这类似于 Python 对空变量的检查。
因此,如果您想围绕变量编写条件逻辑,只需
在这里说“null”或“空字符串”或“未定义”即可有效处理。
In newer JavaScript standards like ES5 and ES6 you can just say
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
here "null" or "empty string" or "undefined" will be handled efficiently.
如果您尝试引用未声明的变量,则所有 JavaScript 实现都会抛出错误。
对象的属性不受相同条件的约束。如果尚未定义对象属性,则尝试访问它时不会抛出错误。因此,在这种情况下,您可以缩短:
考虑到
这一点,并且全局变量可以作为全局对象的属性进行访问(在浏览器中为
window
),您可以使用以下内容对于全局变量:在局部作用域中,确保在代码块的顶部声明变量总是有用的,这将节省
typeof
的重复使用。If you try and reference an undeclared variable, an error will be thrown in all JavaScript implementations.
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:
to
With this in mind, and the fact that global variables are accessible as properties of the global object (
window
in the case of a browser), you can use the following for global variables: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
.首先你必须非常清楚你测试的内容。 JavaScript 具有各种隐式转换,以及两种不同类型的相等比较器:
==
和===
。测试
null
或undefined
的函数test(val)
应该具有以下特征:让我们看看这里的哪些想法实际上通过了我们的测试。测试。
这些有效:
这些无效:
我创建了一个 jsperf 条目来比较这些方法的正确性和性能。目前结果尚无定论,因为在不同浏览器/平台上的运行还不够。请花一点时间在您的计算机上运行测试!
目前看来,简单的
val == null
测试给出了最好的性能。它也是最短的。如果您想要补码,则可以将测试否定为val != null
。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===
.A function,
test(val)
that tests fornull
orundefined
should have the following characteristics:Let's see which of the ideas here actually pass our test.
These work:
These do not work:
I created a jsperf entry to compare the correctness and performance of 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!
At present, it seems that the simple
val == null
test gives the best performance. It's also pretty much the shortest. The test may be negated toval != null
if you want the complement.这是使用数组的另一种方法 includes() 方法:
here's another way using the Array includes() method:
由于没有一个完整且正确的答案,我将尝试总结:
一般来说,表达式:
无法简化,因为
variable
可能未声明,因此省略typeof(variable) ! =“未定义”
将导致ReferenceError。但是,您可以根据上下文简化表达式:如果
变量
是全局,您可以简化为:如果它是 local,你或许可以避免该变量未声明的情况,并且还可以简化为:
如果是对象属性,则不必担心ReferenceError:
Since there is no single complete and correct answer, I will try to summarize:
In general, the expression:
cannot be simplified, because the
variable
might be undeclared so omitting thetypeof(variable) != "undefined"
would result in ReferenceError. But, you can simplify the expression according to the context:If the
variable
is global, you can simplify to:If it is local, you can probably avoid situations when this variable is undeclared, and also simplify to:
If it is object property, you don't have to worry about ReferenceError:
这也是一种很好的(但很冗长)的方式:
发生的事情非常清楚并且很难误解。这非常重要! :-)
这使用
??
运算符 (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator)。如果someObject.someMember
的值为null
或undefined
,则??
运算符将启动并生成值null
。说实话,我喜欢这个东西的明确性,但我通常更喜欢
someObject.someMember == null
,它更具可读性,熟练的 JS 开发人员可能知道这里发生了什么。This is also a nice (but verbose) way of doing it:
It's very clear what's happening and hard to misunderstand. And that can be VERY important! :-)
This uses the
??
operator (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator). If the value ofsomeObject.someMember
isnull
orundefined
, the??
operator kicks in and will make the valuenull
.TBH, I like the explicitness of this thing, but I usualle prefer
someObject.someMember == null
, it's more readable and skilled JS developers probably know what's going on here.这是一个极少数情况下的示例,建议使用
==
而不是===
。表达式somevar == null
将为undefined
和null
返回 true,但对于其他所有内容返回 false(如果变量未声明,则返回错误)。使用
!=
将翻转结果,如预期的那样。现代编辑器不会对使用
==
或!=
运算符与null
发出警告,因为这几乎总是所需的行为。最常见的比较:
自己尝试一下:
This is an example of a very rare occasion where it is recommended to use
==
instead of===
. Expressionsomevar == null
will return true forundefined
andnull
, but false for everything else (an error if variable is undeclared).Using the
!=
will flip the result, as expected.Modern editors will not warn for using
==
or!=
operator withnull
, as this is almost always the desired behavior.Most common comparisions:
Try it yourself:
您只需检查变量是否有值即可。意思是,
如果您不知道变量是否存在(这意味着它是否已声明),您应该使用 typeof 运算符进行检查。例如
You can just check if the variable has a value or not. Meaning,
If you do not know whether a variable exists (that means, if it was declared) you should check with the typeof operator. e.g.
与您所拥有的类似,您可以执行类似
if (some_variable === undefined || some_variable === null) { 的 操作
做事
}
Similar to what you have, you could do something like
if (some_variable === undefined || some_variable === null) {
do stuff
}
无论 yyy 未定义或为 null,它都会返回 true
yes
no
whatever yyy is undefined or null, it will return true
yes
no
在浏览器中打开开发者工具,然后尝试下图所示的代码。
Open the Developer tools in your browser and just try the code shown in the below image.
如果 if 语句的目的是在为变量赋值之前检查
null
或undefined
值,则可以使用 空值合并运算符。根据 caniuse 的数据,应该有大约 85% 的浏览器支持(截至 2021 年 1 月)。该运算符的示例如下所示:如果
some_variable
为null
或,这将确保将变量分配给空字符串(或任何其他默认值) >未定义
。此运算符最适合您的用例,因为它不会返回其他类型的假值(例如
0
和''
)的默认值。If the purpose of the if statement is to check for
null
orundefined
values before assigning a value to a variable, you can make use of the Nullish Coalescing Operator. According to the data from caniuse, it should be supported by around 85% of the browsers(as of January 2021). An example of the operator is shown below:This will ensure that the variable will be assigned to an empty string (or any other default value) if
some_variable
isnull
orundefined
.This operator is most suited for your use case, as it does not return the default value for other types of falsy value such as
0
and''
.如果值不是以下值,上面的代码将计算为 true:
Above code will evaluate to true if value is not:
正如其中一个答案中提到的,如果您谈论的是具有全局作用域的变量,那么您可能会很幸运。您可能知道,您全局定义的变量往往会添加到 windows 对象中。您可以利用这一事实,假设您正在访问一个名为 bleh 的变量,只需使用双倒置运算符 (!!),
当 bleh 尚未声明并赋值时,这将返回 false。
As mentioned in one of the answers, you can be in luck if you are talking about a variable that has a global scope. As you might know, the variables that you define globally tend to get added to the windows object. You can take advantage of this fact so lets say you are accessing a variable called bleh, just use the double inverted operator (!!)
This would return a false while bleh has not been declared AND assigned a value.
为了理解,让我们分析一下 Javascript 引擎在转换 undefined 、 null 和 '' (也是一个空字符串)时返回的值是什么。您可以直接在开发者控制台上进行检查。
你可以看到所有都转换为 false ,意味着所有这三个都通过 javascript 假设“不存在”。因此,您无需像下面这样显式检查代码中的所有三个。
我还想指出一件事。
Boolean(0) 的结果是什么?
当然是假的。当 0 是预期结果中的有效值时,这会在代码中产生错误。因此,请确保在编写代码时检查这一点。
In order to understand, Let's analyze what will be the value return by the Javascript Engine when converting undefined , null and ''(An empty string also). You can directly check the same on your developer console.
You can see all are converting to false , means All these three are assuming ‘lack of existence’ by javascript. So you no need to explicitly check all the three in your code like below.
Also I want to point out one more thing.
What will be the result of Boolean(0)?
Of course false. This will create a bug in your code when 0 is a valid value in your expected result. So please make sure you check for this when you write the code.
使用 Ramda,您只需执行
R.isNil(yourValue)
Lodash 和其他辅助库具有相同的功能。
With Ramda, you can simply do
R.isNil(yourValue)
Lodash and other helper libraries have the same function.
您可以使用
lodash
库。_.isNil(value)
为null
和undefined
提供true
测试 - https://bazinga.tools/lodash
You can make use of
lodash
library._.isNil(value)
givestrue
for bothnull
andundefined
Test on - https://bazinga.tools/lodash
我已经使用此方法
将 id 保存在某个变量中
然后使用 if 条件来完成此操作
I have done this using this method
save the id in some variable
then use if condition
在 ES5 或 ES6 中,如果您需要多次检查,可以这样做:
In ES5 or ES6 if you need check it several times you cand do:
例如,我复制 vladernn 的答案进行测试,您也可以单击“复制代码片段以回答”按钮来测试。
for example I copy vladernn's answer to test, u can just click button "Copy snippets to answer" to test too .
您可以将以下内容与空合并一起使用
you could use the following with nullish coalescing
测试无效 (
if (value == null)
) 或非无效 (if (value != null)
) 比测试变量的定义状态更简洁。此外,如果使用布尔值定义变量(或对象属性),则测试
if (value)
(或if( obj.property)
)来确保变量(或对象属性)是否存在会失败false
值。买者自负:)Testing nullity (
if (value == null)
) or non-nullity (if (value != null)
) is less verbose than testing the definition status of a variable.Moreover, testing
if (value)
(orif( obj.property)
) to ensure the existence of your variable (or object property) fails if it is defined with a booleanfalse
value. Caveat emptor :)将 undefined 或 null 或 0 与 ES5 和 ES6 标准进行比较的最佳方式
Best way to compare undefined or null or 0 with ES5 and ES6 standards
您必须定义以下形式的函数:
You must define a function of this form:
通过使用严格比较运算符可以轻松区分这两个值。
示例代码:
Both values can be easily distinguished by using the strict comparison operator.
Sample Code: