如何确定变量是未定义的还是空的?
我的代码如下:
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解释器将停止执行。
当前回答
在JavaScript中,据我所知,我们可以检查如下未定义的、空的或空的变量。
if (variable === undefined){
}
if (variable === null){
}
if (variable === ''){
}
检查所有条件:
if(variable === undefined || variable === null || variable === ''){
}
其他回答
您可以使用抽象相等运算符的特性来执行此操作:
if (variable == null){
// your code here.
}
因为null==undefined为true,所以上面的代码将捕获null和undefineed。
如果创建一个函数来检查它:
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;
}
您可以通过简单地使用typeof:
if(typeof value == 'undefined'){
jQuery检查元素不为空:
var dvElement = $('#dvElement');
if (dvElement.length > 0) {
// Do something
}
else{
// Else do something else
}
为了测试变量是否为空或未定义,我使用以下代码。
if(typeof sVal === 'undefined' || sVal === null || sVal === ''){
console.log('variable is undefined or null');
}