如何确定变量是未定义的还是空的?
我的代码如下:
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 || x === undefined) {
// Add your response code here, etc.
}
来源:https://www.growthsnippets.com/how-can-i-determine-if-a-variable-is-undefined-or-null/
其他回答
调用typeof null返回“object”值,因为特殊值null被认为是空对象引用。Safari到第5版和Chrome到第7版都有一个怪癖,在正则表达式上调用typeof返回“function”,而所有其他浏览器都返回“object”。
最简单的检查方法是:
if(!variable) {
// If the variable is null or undefined then execution of code will enter here.
}
由于使用的是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 (x === null || x === undefined) {
// Add your response code here, etc.
}
来源:https://www.growthsnippets.com/how-can-i-determine-if-a-variable-is-undefined-or-null/
jQuery检查元素不为空:
var dvElement = $('#dvElement');
if (dvElement.length > 0) {
// Do something
}
else{
// Else do something else
}