如何确定变量是未定义的还是空的?
我的代码如下:
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解释器将停止执行。
当前回答
var x;
if (x === undefined) {
alert ("only declared, but not defined.")
};
if (typeof y === "undefined") {
alert ("not even declared.")
};
您只能使用第二个:因为它将检查定义和声明
其他回答
最简单的检查方法是:
if(!variable) {
// If the variable is null or undefined then execution of code will enter here.
}
var i;
if (i === null || typeof i === 'undefined') {
console.log(i, 'i is undefined or null')
}
else {
console.log(i, 'i has some value')
}
如果创建一个函数来检查它:
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;
}
if (typeof EmpName != 'undefined' && EmpName) {
如果值不是:
无效的未定义NaN公司空字符串(“”)0假的
if(x==null)在JavaScript中是个坏主意。使用“==”判断-它可能会导致意外的类型强制,并且CoffeeScript无法读取它,决不能在条件判断中使用“==”或“!=”!
if(x)会更好,但要注意0和“”。它将被视为false,而不是“!=null”的equal方法为true。
请参阅JavaScript最佳实践。