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

JavaScript

卡卡西Sam

2020-03-09

如何确定变量is undefinednull

我的代码如下:

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

但是,如果执行此操作,JavaScript解释器将停止执行。

第206篇《如何确定变量是“未定义”还是“空”?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

9个回答
飞云前端西门 2020.03.09
var x;
if (x === undefined) {
    alert ("only declared, but not defined.")
};
if (typeof y === "undefined") {
    alert ("not even declared.")
};

You can only use second one: as it will check for both definition and declaration

Monkey洋 2020.03.09
(null == undefined)  // true

(null === undefined) // false

Because === checks for both the type and value. Type of both are different but value is the same.

Tom小宇宙 2020.03.09

Calling typeof null returns a value of “object”, as the special value null is considered to be an empty object reference. Safari through version 5 and Chrome through version 7 have a quirk where calling typeof on a regular expression returns “function” while all other browsers return “object”.

null 2020.03.09

You can simply use the following (I know there are shorter ways to do this, but this may make it easier to visually observe, at least for others looking at the code).

if (x === null || x === undefined) {
 // Add your response code here, etc.

}

Harry神奇 2020.03.09

I run this test in the Chrome console. Using (void 0) you can check undefined:

var c;
undefined
if (c === void 0) alert();
// output =  undefined
var c = 1;
// output =  undefined
if (c === void 0) alert();
// output =   undefined
// check c value  c
// output =  1
if (c === void 0) alert();
// output =  undefined
c = undefined;
// output =  undefined
if (c === void 0) alert();
// output =   undefined
GilJinJin 2020.03.09

In JavaScript, as per my knowledge, we can check an undefined, null or empty variable like below.

if (var === undefined){
}

if (var === null){
}

if (var === ''){
}

Check all conditions:

if(var === undefined || var === null || var === ''){
}
老丝村村 2020.03.09

The easiest way to check is:

if(!variable) {
  // If the variable is null or undefined then execution of code will enter here.
}
SamGreen 2020.03.09

The shortest and easiest:

if(!EmpName ){
 // DO SOMETHING
}

this will evaluate true if EmpName is:

  • null
  • undefined
  • NaN
  • empty
  • string ("")
  • 0
  • false
神无逆天GO 2020.03.09

您可以使用抽象相等运算符的品质来做到这一点:

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

因为null == undefined为true,所以上面的代码将同时捕获nullundefined

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android