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

我的代码如下:

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 (object) {
    // Your code
}

例如:

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

其他回答

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

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

因为null==undefined为true,所以上面的代码将捕获null和undefineed。

jQueryattr()函数返回一个空字符串或实际值(绝对不能为空或未定义)。它返回undefined的唯一时间是选择器没有返回任何元素。

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

if (!EmpName) { //do something }

if(x==null)在JavaScript中是个坏主意。使用“==”判断-它可能会导致意外的类型强制,并且CoffeeScript无法读取它,决不能在条件判断中使用“==”或“!=”!

if(x)会更好,但要注意0和“”。它将被视为false,而不是“!=null”的equal方法为true。

请参阅JavaScript最佳实践。

我在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

最佳方式:

if(typeof variable==='undefined' || variable===null) {

/* do your stuff */
}