如何确定变量是未定义的还是空的?
我的代码如下:
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解释器将停止执行。
当前回答
你可以这样做,我认为在一个条件下对同一变量进行多值检查更有效
const x = undefined;
const y = null;
const z = 'test';
if ([undefined, null].includes(x)) {
// Will return true
}
if ([undefined, null].includes(y)) {
// Will return true
}
if ([undefined, null].includes(z)) {
// Will return false
}
其他回答
由于使用的是jQuery,因此可以通过使用单个函数来确定变量是未定义的还是其值为空。
var s; // undefined
jQuery.isEmptyObject(s); // will return true;
s = null; // defined as null
jQuery.isEmptyObject(s); // will return true;
// usage
if(jQuery.isEmptyObject(s)){
alert('Either variable: s is undefined or its value is null');
}else{
alert('variable: s has value ' + s);
}
s = 'something'; // defined with some value
jQuery.isEmptyObject(s); // will return false;
为了测试变量是否为空或未定义,我使用以下代码。
if(typeof sVal === 'undefined' || sVal === null || sVal === ''){
console.log('variable is undefined or null');
}
foo==null检查应该能做到这一点,并以最短的方式解决“undefined OR null”情况。(不考虑“foo is Not declarated”的情况。)但习惯于使用3等于(作为最佳实践)的人可能不会接受它。只需看看eslint和tslint中的eqeqeq或三等于规则。。。
在这种情况下,当我们分别检查变量是否未定义或为空时,应采用显式方法,我对本主题的贡献(目前有27个非否定答案!)是使用void 0作为执行未定义检查的简短而安全的方法。
使用foo==undefined是不安全的,因为undefineed不是保留字,可以被隐藏(MDN)。使用typeof==“undefined”检查是安全的,但如果我们不关心foo是否未声明,则可以使用以下方法:
if (foo === void 0 || foo === null) { ... }
if (typeof EmpName != 'undefined' && EmpName) {
如果值不是:
无效的未定义NaN公司空字符串(“”)0假的
在JavaScript中,据我所知,我们可以检查如下未定义的、空的或空的变量。
if (variable === undefined){
}
if (variable === null){
}
if (variable === ''){
}
检查所有条件:
if(variable === undefined || variable === null || variable === ''){
}