如何在 JavaScript 中检查变量是否为空和/或未定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12271750/
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 07:34:43  来源:igfitidea点击:

How to check if a variable is both null and /or undefined in JavaScript

javascriptjquery

提问by PMat

Possible Duplicate:
Detecting an undefined object property in JavaScript
How to determine if variable is 'undefined' or 'null'
Is there a standard function to check for null, undefined, or blank variables in JavaScript?

可能的重复:
在 JavaScript 中检测未定义的对象属性
如何确定变量是“未定义”还是“空”
是否有标准函数来检查 JavaScript 中的空、未定义或空白变量?

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.

但不是分两步进行,即检查它是否未定义且不为空。是否有一步检查可以代替此检查。

回答by Pointy

A variable cannot be both nulland undefinedat the same time. However, the direct answer to your question is:

变量不能同时nullundefined在同一时间。但是,您问题的直接答案是:

if (variable != null)

One =, not two.

一个=,不是两个。

There are two special clauses in the "abstract equality comparison algorithm" in the JavaScript spec devoted to the case of one operand being nulland the other being undefined, and the result is truefor ==and falsefor !=. Thus if the value of the variable is undefined, it's not != null, and if it's not null, it's obviously not != null.

JavaScript 规范中的“抽象相等比较算法”中有两个特殊子句,专门针对一个操作数为null另一个为 的情况undefined,结果为truefor==falsefor !=。因此,如果变量的值是undefined,则它不是!= null,如果它不为空,则显然不是!= null

Now, the case of an identifier not being defined at all, either as a varor 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:

现在,完全没有定义标识符的情况,无论是作为 avarlet,作为函数参数,还是作为全局上下文的属性是不同的。对此类标识符的引用在运行时被视为错误。您可以尝试引用并捕获错误:

var isDefined = false;
try {
  (variable);
  isDefined = true;
}
catch (x) {}

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 windowproperty (in browser JavaScript):

然而,我个人认为这是一种有问题的做法。对于根据其他库的存在或不存在或某些类似情况可能存在或可能存在的全局符号,您可以测试window属性(在浏览器 JavaScript 中):

var isJqueryAvailable = window.jQuery != null;

or

或者

var isJqueryAvailable = "jQuery" in window;

回答by KDaker

You can wrap it in your own function:

您可以将其包装在您自己的函数中:

function isNullAndUndef(variable) {

    return (variable !== null && variable !== undefined);
}