如何确定变量是未定义的还是空的?
我的代码如下:
var EmpName = $("div#esd-names div#name").attr('class');
if(EmpName == 'undefined'){
// DO SOMETHING
};
<div id="esd-names">
<div id="name"></div>
</div>
但如果我这样做,JavaScript解释器将停止执行。
如何确定变量是未定义的还是空的?
我的代码如下:
var EmpName = $("div#esd-names div#name").attr('class');
if(EmpName == 'undefined'){
// DO SOMETHING
};
<div id="esd-names">
<div id="name"></div>
</div>
但如果我这样做,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 (variable == null){
// your code here.
}
因为null==undefined为true,所以上面的代码将捕获null和undefineed。
最佳方式:
if(typeof variable==='undefined' || variable===null) {
/* do your stuff */
}
var i;
if (i === null || typeof i === 'undefined') {
console.log(i, 'i is undefined or null')
}
else {
console.log(i, 'i has some value')
}
if(x==null)在JavaScript中是个坏主意。使用“==”判断-它可能会导致意外的类型强制,并且CoffeeScript无法读取它,决不能在条件判断中使用“==”或“!=”!
if(x)会更好,但要注意0和“”。它将被视为false,而不是“!=null”的equal方法为true。
请参阅JavaScript最佳实践。
为了测试变量是否为空或未定义,我使用以下代码。
if(typeof sVal === 'undefined' || sVal === null || sVal === ''){
console.log('variable is undefined or null');
}