Javascript 如何确定变量是“未定义”还是“空”?

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

How can I determine if a variable is 'undefined' or 'null'?

javascriptjqueryvariablesnullundefined

提问by sadmicrowave

How do I determine if variable is undefinedor null?

我如何确定变量是undefined还是null

My code is as follows:

我的代码如下:

var EmpName = $("div#esd-names div#name").attr('class');
if(EmpName == 'undefined'){
  // DO SOMETHING
};
<div id="esd-names">
  <div id="name"></div>
</div>

But if I do this, the JavaScript interpreter halts execution.

但是如果我这样做,JavaScript 解释器就会停止执行。

回答by Sarfraz

You can use the qualities of the abstract equality operatorto do this:

您可以使用抽象相等运算符的特性来执行此操作:

if (variable == null){
    // your code here.
}

Because null == undefinedis true, the above code will catch both nulland undefined.

因为null == undefined是真的,上面的代码将同时捕获nullundefined

回答by temporary_user_name

The standard way to catch nulland undefinedsimultaneously is this:

同时捕获null和捕获的标准方法undefined是:

if (variable == null) {
     // do something 
}

--which is 100% equivalent to the more explicit but less concise:

-- 这 100% 相当于更明确但不那么简洁的:

if (variable === undefined || variable === null) {
     // do something 
}

When writing professional JS, it's taken for granted that type equality and the behavior of ==vs ===is understood. Therefore we use ==and only compare to null.

在编写专业的 JS 时,类型相等和==vs的行为是===理所当然的。因此,我们使用==并且仅与 进行比较null



Edit again

再次编辑

The comments suggesting the use of typeofare simply wrong.Yes, my solution above will cause a ReferenceError if the variable doesn't exist. This is a good thing.This ReferenceError is desirable: it will help you find your mistakes and fix them before you ship your code, just like compiler errors would in other languages. Use try/catchif you are working with input you don't have control over.

建议使用 的评论typeof是完全错误的。是的,如果变量不存在,我上面的解决方案将导致 ReferenceError。这是一件好事。这个 ReferenceError 是可取的:它会帮助您在发布代码之前找到错误并修复它们,就像其他语言中的编译器错误一样。如果您正在处理您无法控制的输入,请使用try/ catch

You should not have any references to undeclared variables in your code.

您不应在代码中引用任何未声明的变量。

回答by jkindwall

Combining the above answers, it seems the most complete answer would be:

结合以上答案,似乎最完整的答案是:

if( typeof variable === 'undefined' || variable === null ){
    // Do stuff
}

This should work for any variable that is either undeclared or declared and explicitly set to null or undefined. The boolean expression should evaluate to false for any declared variable that has an actual non-null value.

这应该适用于任何未声明或声明并显式设置为 null 或未定义的变量。对于任何具有实际非空值的声明变量,布尔表达式应评估为 false。

回答by jkindwall

if (variable == null) {
    // Do stuff, will only match null or undefined, this won't match false
}

回答by Thamaraiselvam

if (typeof EmpName != 'undefined' && EmpName) {

will evaluate to true if value is not:

如果 value 不是,则评估为 true:

  • null

  • undefined

  • NaN

  • empty string ("")

  • 0

  • false

  • 空值

  • 不明确的

  • NaN

  • 空字符串 ("")

  • 0

  • 错误的

回答by Chetan Sastry

jQuery attr()function returns either a blank string or the actual value (and never nullor undefined). The only time it returns undefinedis when your selector didn't return any element.

jQueryattr()函数返回空字符串或实际值(从不nullundefined)。它返回的唯一时间undefined是您的选择器没有返回任何元素。

So you may want to test against a blank string. Alternatively, since blank strings, null and undefined are false-y, you can just do this:

因此,您可能想要针对空白字符串进行测试。或者,由于空字符串、null 和 undefined 是 false-y,您可以这样做:

if (!EmpName) { //do something }

回答by phil294

I've come to write my own function for this. JavaScript is weird.

我是来为此编写自己的函数的。JavaScript 很奇怪。

It is usable on literally anything. (Note that this also checks if the variable contains any usable values. But since this information is usually also needed, I think it's worth posting). Please consider leaving a note.

它可以用于任何东西。(请注意,这还会检查变量是否包含任何可用。但由于通常也需要此信息,因此我认为值得发布)。请考虑留下便条。

function empty(v) {
    let type = typeof v;
    if (type === 'undefined') {
        return true;
    }
    if (type === 'boolean') {
        return !v;
    }
    if (v === null) {
        return true;
    }
    if (v === undefined) {
        return true;
    }
    if (v instanceof Array) {
        if (v.length < 1) {
            return true;
        }
    } else if (type === 'string') {
        if (v.length < 1) {
            return true;
        }
        if (v === '0') {
            return true;
        }
    } else if (type === 'object') {
        if (Object.keys(v).length < 1) {
            return true;
        }
    } else if (type === 'number') {
        if (v === 0) {
            return true;
        }
    }
    return false;
}

TypeScript-compatible.

与 TypeScript 兼容。



This function should do exactlythe same thing like PHP's empty()function(see RETURN VALUES)

这个函数应该做与 PHP函数完全相同的事情(请参阅 参考资料)empty()RETURN VALUES

Considers undefined, null, false, 0, 0.0, "0"{}, []as empty.

认为undefined, null, false, 0, 0.0, "0"{},[]为空。

"0.0", NaN, " ", trueare considered non-empty.

"0.0", NaN, " ",true被认为是非空的。

回答by DenisS

If the variable you want to check is a global, do

如果要检查的变量是全局变量,请执行

if (window.yourVarName) {
    // Your code here
}

This way to check will not throw an error even if the yourVarNamevariable doesn't exist.

即使yourVarName变量不存在,这种检查方式也不会抛出错误。

Example: I want to know if my browser supports History API

示例:我想知道我的浏览器是否支持 History API

if (window.history) {
    history.back();
}

How this works:

这是如何工作的:

windowis an object which holds all global variables as its properties, and in JavaScript it is legal to try to access a non-existing object property. If historydoesn't exist then window.historyreturns undefined. undefinedis falsey, so code in an if(undefined){}block won't run.

window是一个拥有所有全局变量作为其属性的对象,在 JavaScript 中尝试访问不存在的对象属性是合法的。如果history不存在则window.history返回undefinedundefined是假的,所以if(undefined){}块中的代码不会运行。

回答by userPlus

The shortest and easiest:

最短和最简单的:

if(!EmpName ){
 // DO SOMETHING
}

this will evaluate true if EmpName is:

如果 EmpName 是:

  • null
  • undefined
  • NaN
  • empty
  • string ("")
  • 0
  • false
  • 空值
  • 不明确的
  • NaN
  • 空的
  • 细绳 (””)
  • 0
  • 错误的

回答by Kamil Kie?czewski

Probably the shortest way to do this is:

可能做到这一点的最短方法是:

if(EmpName == null) { /* DO SOMETHING */ };

Here is proof:

这是证明:

function check(EmpName) {
  if(EmpName == null) { return true; };
  return false;
}

var log = (t,a) => console.log(`${t} -> ${check(a)}`);

log('null', null);
log('undefined', undefined);
log('NaN', NaN);
log('""', "");
log('{}', {});
log('[]', []);
log('[1]', [1]);
log('[0]', [0]);
log('[[]]', [[]]);
log('true', true);
log('false', false);
log('"true"', "true");
log('"false"', "false");
log('Infinity', Infinity);
log('-Infinity', -Infinity);
log('1', 1);
log('0', 0);
log('-1', -1);
log('"1"', "1");
log('"0"', "0");
log('"-1"', "-1");

// "void 0" case
console.log('---\n"true" is:', true);
console.log('"void 0" is:', void 0);
log(void 0,void 0); // "void 0" is "undefined" 

And here are more details about ==(source here)

这里有更多关于==(来源在这里)的详细信息

Enter image description here

在此处输入图片说明

BONUS: reason why ===is more clear than ==(look on agc answer)

奖励:原因=====(查看agc 答案)更清楚

Enter image description here

在此处输入图片说明