如何确定变量是未定义的还是空的?
我的代码如下:
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(x==null)在JavaScript中是个坏主意。使用“==”判断-它可能会导致意外的类型强制,并且CoffeeScript无法读取它,决不能在条件判断中使用“==”或“!=”!
if(x)会更好,但要注意0和“”。它将被视为false,而不是“!=null”的equal方法为true。
请参阅JavaScript最佳实践。
其他回答
最简单的检查方法是:
if(!variable) {
// If the variable is null or undefined then execution of code will enter here.
}
调用typeof null返回“object”值,因为特殊值null被认为是空对象引用。Safari到第5版和Chrome到第7版都有一个怪癖,在正则表达式上调用typeof返回“function”,而所有其他浏览器都返回“object”。
var x;
if (x === undefined) {
alert ("only declared, but not defined.")
};
if (typeof y === "undefined") {
alert ("not even declared.")
};
您只能使用第二个:因为它将检查定义和声明
为了测试变量是否为空或未定义,我使用以下代码。
if(typeof sVal === 'undefined' || sVal === null || sVal === ''){
console.log('variable is undefined or null');
}
您可以通过简单地使用typeof:
if(typeof value == 'undefined'){