如何在JavaScript中检查变量是否为空和/或未定义 [英] How to check if a variable is both null and /or undefined in JavaScript
问题描述
可能重复:
在JavaScript中检测未定义的对象属性
如何确定变量是'undefined'还是'null'
是否有一个标准函数来检查JavaScript中的null,undefined或blank变量?
在我的代码中,我的条件看起来像
In my code, I have a condition that looks like
if (variable !== null && variable !== undefined) {
}
但不是分两步完成,即检查它是否未定义且不为空。是否有一步检查取代此检查。
But instead of doing it in two steps, i.e checking if it is not defined and not null. Is there a one step checking that replaces this check.
推荐答案
变量不能同时为 null
和 undefined
同时。但是,您问题的直接答案是:
A variable cannot be both null
and undefined
at the same time. However, the direct answer to your question is:
if (variable != null)
一个 =
,而不是两个。
JavaScript规范中的抽象相等比较算法中有两个特殊条款,专门用于一个操作数 null
的情况,另一个是 undefined
,结果是 true
for ==
和 false
for !=
。因此,如果变量的值是 undefined
,那么它不是!= null
,如果它不是null,那么显然不是!= null
。
There are two special clauses in the "abstract equality comparison algorithm" in the JavaScript spec devoted to the case of one operand being null
and the other being undefined
, and the result is true
for ==
and false
for !=
. Thus if the value of the variable is undefined
, it's not != null
, and if it's not null, it's obviously not != null
.
现在,根本没有定义标识符的情况,作为 var
或 let
,作为函数参数,或作为全局上下文的属性是不同。对此类标识符的引用在运行时被视为错误。您可以尝试引用并捕获错误:
Now, the case of an identifier not being defined at all, either as a var
or let
, as a function parameter, or as a property of the global context is different. A reference to such an identifier is treated as an error at runtime. You could attempt a reference and catch the error:
var isDefined = false;
try {
(variable);
isDefined = true;
}
catch (x) {}
我个人认为是然而,有问题的做法。对于可能存在或可能存在某些其他库或某些类似情况的全局符号,您可以测试窗口
属性(在浏览器JavaScript中) :
I would personally consider that a questionable practice however. For global symbols that may or may be there based on the presence or absence of some other library, or some similar situation, you can test for a window
property (in browser JavaScript):
var isJqueryAvailable = window.jQuery != null;
或
var isJqueryAvailable = "jQuery" in window;
这篇关于如何在JavaScript中检查变量是否为空和/或未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!