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

我的代码如下:

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

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


当前回答

您可以简单地使用以下方法(我知道有更短的方法可以做到这一点,但这可能会使视觉观察更容易,至少对其他查看代码的人来说是如此)。

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

来源:https://www.growthsnippets.com/how-can-i-determine-if-a-variable-is-undefined-or-null/

其他回答

我刚刚遇到了这个问题,即检查对象是否为空。我只使用这个:

if (object) {
    // Your code
}

例如:

if (document.getElementById("enterJob")) {
    document.getElementById("enterJob").className += ' current';
}

可能最短的方法是:

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

这里有证据:

功能检查(EmpName){如果(EmpName==null){return true;};return false;}var log=(t,a)=>console.log(`${t}->${check(a)}`);log('ull',null);log('未定义',未定义);日志('NaN',NaN);日志('“”,“”);日志(“{}”,{});日志('[]',[]);日志(“[1]”,[1]);日志(“[0]”,[0]);日志('[[]]',[[]]);log('true',true);日志('false',false);log('“true”',“true”);日志('“false”',“false”);log(“不确定性”,无限);log('-无限',-无限);日志('1',1);日志('0',0);日志('-1',-1);日志(“1”,“1”);日志(“0”,“0”);日志('“-1”',“-1”);//“void 0”案例console.log('---\n“true”为:',true);console.log('“void 0”为:',void 0);日志(void 0,void 0);//“void 0”为“undefined”

下面是关于==的更多详细信息(来源于此处)

奖金:为什么==比==更清楚(看看agc的答案)

最简单的检查方法是:

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

最简单的答案:

if(!EmpName){
  // DO SOMETHING
};

我在Chrome控制台上运行这个测试。使用(void 0)可以检查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