如何确定变量是未定义的还是空的?
我的代码如下:
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解释器将停止执行。
当前回答
结合以上答案,似乎最完整的答案是:
if( typeof variable === 'undefined' || variable === null ){
// Do stuff
}
这应该适用于任何未声明或已声明且显式设置为null或undefined的变量。对于具有实际非空值的任何声明变量,布尔表达式的计算结果应为false。
其他回答
为了测试变量是否为空或未定义,我使用以下代码。
if(typeof sVal === 'undefined' || sVal === null || sVal === ''){
console.log('variable is undefined or null');
}
您可以通过简单地使用typeof:
if(typeof value == 'undefined'){
最佳方式:
if(typeof variable==='undefined' || variable===null) {
/* do your stuff */
}
我在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
如果创建一个函数来检查它:
export function isEmpty (v) {
if (typeof v === "undefined") {
return true;
}
if (v === null) {
return true;
}
if (typeof v === "object" && Object.keys(v).length === 0) {
return true;
}
if (Array.isArray(v) && v.length === 0) {
return true;
}
if (typeof v === "string" && v.trim().length === 0) {
return true;
}
return false;
}