如何确定变量是未定义的还是空的?
我的代码如下:
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(EmpName == null) { /* DO SOMETHING */ };
这里有证据:
功能检查(EmpName){如果(EmpName==null){return true;};return false;}var log=(t,a)=>console.log(`${t}->${check(a)}`);log('ull',null);log('未定义',未定义);日志('NaN',NaN);日志('“”,“”);日志(“{}”,{});日志('[]',[]);日志(“[1]”,[1]);日志(“[0]”,[0]);日志('[[]]',[[]]);log('true',true);日志('false',false);log('“true”',“true”);日志('“false”',“false”);log(“不确定性”,无限);log('-无限',-无限);日志('1',1);日志('0',0);日志('-1',-1);日志(“1”,“1”);日志(“0”,“0”);日志('“-1”',“-1”);//“void 0”案例console.log('---\n“true”为:',true);console.log('“void 0”为:',void 0);日志(void 0,void 0);//“void 0”为“undefined”
下面是关于==的更多详细信息(来源于此处)
奖金:为什么==比==更清楚(看看agc的答案)
其他回答
由于使用的是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;
在JavaScript中,据我所知,我们可以检查如下未定义的、空的或空的变量。
if (variable === undefined){
}
if (variable === null){
}
if (variable === ''){
}
检查所有条件:
if(variable === undefined || variable === null || variable === ''){
}
if(x==null)在JavaScript中是个坏主意。使用“==”判断-它可能会导致意外的类型强制,并且CoffeeScript无法读取它,决不能在条件判断中使用“==”或“!=”!
if(x)会更好,但要注意0和“”。它将被视为false,而不是“!=null”的equal方法为true。
请参阅JavaScript最佳实践。
var x;
if (x === undefined) {
alert ("only declared, but not defined.")
};
if (typeof y === "undefined") {
alert ("not even declared.")
};
您只能使用第二个:因为它将检查定义和声明
我刚刚遇到了这个问题,即检查对象是否为空。我只使用这个:
if (object) {
// Your code
}
例如:
if (document.getElementById("enterJob")) {
document.getElementById("enterJob").className += ' current';
}