如何确定变量是未定义的还是空的?
我的代码如下:
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的答案)
其他回答
同时捕获null和undefined的标准方法是:
if (variable == null) {
// do something
}
--这100%等同于更明确但不那么简洁的:
if (variable === undefined || variable === null) {
// do something
}
在编写专业JS时,类型平等和==vs==的行为被理解是理所当然的。因此,我们使用==,并且只与null进行比较。
再次编辑
建议使用typeof的评论完全是错误的。是的,如果变量不存在,我上面的解决方案将导致ReferenceError。这是一件好事。这个ReferenceError是可取的:它将帮助您在发布代码之前找到错误并修复它们,就像其他语言中的编译器错误一样。如果您正在处理无法控制的输入,请使用try/catch。
代码中不应该有任何对未声明变量的引用。
结合以上答案,似乎最完整的答案是:
if( typeof variable === 'undefined' || variable === null ){
// Do stuff
}
这应该适用于任何未声明或已声明且显式设置为null或undefined的变量。对于具有实际非空值的任何声明变量,布尔表达式的计算结果应为false。
使用以下解决方案:
const getType = (val) => typeof val === 'undefined' || !val ? null : typeof val;
const isDeepEqual = (a, b) => getType(a) === getType(b);
console.log(isDeepEqual(1, 1)); // true
console.log(isDeepEqual(null, null)); // true
console.log(isDeepEqual([], [])); // true
console.log(isDeepEqual(1, "1")); // false
etc...
我可以检查以下内容:
无效的未定义NaN公司空的字符串(“”)0假的
最简单的检查方法是:
if(!variable) {
// If the variable is null or undefined then execution of code will enter here.
}
if(x==null)在JavaScript中是个坏主意。使用“==”判断-它可能会导致意外的类型强制,并且CoffeeScript无法读取它,决不能在条件判断中使用“==”或“!=”!
if(x)会更好,但要注意0和“”。它将被视为false,而不是“!=null”的equal方法为true。
请参阅JavaScript最佳实践。