如何确定变量是未定义的还是空的?
我的代码如下:
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(!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;
让我们看看这个,
让苹果;//只将变量声明为apple警报(苹果);//未定义在上文中,变量仅声明为apple。在这种情况下,如果我们调用方法alert,它将显示undefined。 让apple=null;/*将变量声明为apple并初始化,但值为空*/警报(苹果);//无效的
第二个显示为空,因为apple值的变量为空。
因此,您可以检查值是未定义的还是空的。
if(apple !== undefined || apple !== null) {
// Can use variable without any error
}
最短最简单的:
if(!EmpName ){
// DO SOMETHING
}
如果EmpName为:
无效的未定义NaN公司空的字符串(“”)0假的
if (typeof EmpName != 'undefined' && EmpName) {
如果值不是:
无效的未定义NaN公司空字符串(“”)0假的
您可以简单地使用以下方法(我知道有更短的方法可以做到这一点,但这可能会使视觉观察更容易,至少对其他查看代码的人来说是如此)。
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/