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

如何确定变量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解释器将停止执行。

飞云前端西门2020/03/09 18:24:57
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 18:24:57
(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 18:24:57

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”.

2020/03/09 18:24:57

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 18:24:57

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
GilJinJin2020/03/09 18:24:57

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 18:24:57

The easiest way to check is:

if(!variable) {
  // If the variable is null or undefined then execution of code will enter here.
}
SamGreen2020/03/09 18:24:57

The shortest and easiest:

if(!EmpName ){
 // DO SOMETHING
}

this will evaluate true if EmpName is:

  • null
  • undefined
  • NaN
  • empty
  • string ("")
  • 0
  • false
神无逆天GO2020/03/09 18:24:57

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

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

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