如何确定变量是未定义的还是空的?
我的代码如下:
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 (window.yourVarName) {
// Your code here
}
即使yourVarName变量不存在,这种检查方法也不会引发错误。
示例:我想知道我的浏览器是否支持历史API
if (window.history) {
history.back();
}
工作原理:
窗口是一个对象,它保存所有全局变量作为其财产,在JavaScript中,尝试访问一个不存在的对象属性是合法的。如果历史记录不存在,则window.history返回undefined。undefined为false,因此if(undefineed){}块中的代码不会运行。
其他回答
由于使用的是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 (variable == null){
// your code here.
}
因为null==undefined为true,所以上面的代码将捕获null和undefineed。
最简单的检查方法是:
if(!variable) {
// If the variable is null or undefined then execution of code will enter here.
}
(null == undefined) // true
(null === undefined) // false
因为==检查类型和值。两者的类型不同,但值相同。
同时捕获null和undefined的标准方法是:
if (variable == null) {
// do something
}
--这100%等同于更明确但不那么简洁的:
if (variable === undefined || variable === null) {
// do something
}
在编写专业JS时,类型平等和==vs==的行为被理解是理所当然的。因此,我们使用==,并且只与null进行比较。
再次编辑
建议使用typeof的评论完全是错误的。是的,如果变量不存在,我上面的解决方案将导致ReferenceError。这是一件好事。这个ReferenceError是可取的:它将帮助您在发布代码之前找到错误并修复它们,就像其他语言中的编译器错误一样。如果您正在处理无法控制的输入,请使用try/catch。
代码中不应该有任何对未声明变量的引用。