如何确定变量是未定义的还是空的?
我的代码如下:
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解释器将停止执行。
当前回答
调用typeof null返回“object”值,因为特殊值null被认为是空对象引用。Safari到第5版和Chrome到第7版都有一个怪癖,在正则表达式上调用typeof返回“function”,而所有其他浏览器都返回“object”。
其他回答
我在Chrome控制台上运行这个测试。使用(void 0)可以检查undefined:
var c;
undefined
if (c === void 0) alert();
// output = undefined
var c = 1;
// output = undefined
if (c === void 0) alert();
// output = undefined
// check c value c
// output = 1
if (c === void 0) alert();
// output = undefined
c = undefined;
// output = undefined
if (c === void 0) alert();
// output = undefined
让我们看看这个,
让苹果;//只将变量声明为apple警报(苹果);//未定义在上文中,变量仅声明为apple。在这种情况下,如果我们调用方法alert,它将显示undefined。 让apple=null;/*将变量声明为apple并初始化,但值为空*/警报(苹果);//无效的
第二个显示为空,因为apple值的变量为空。
因此,您可以检查值是未定义的还是空的。
if(apple !== undefined || apple !== null) {
// Can use variable without any error
}
如果要检查的变量是全局变量,请执行
if (window.yourVarName) {
// Your code here
}
即使yourVarName变量不存在,这种检查方法也不会引发错误。
示例:我想知道我的浏览器是否支持历史API
if (window.history) {
history.back();
}
工作原理:
窗口是一个对象,它保存所有全局变量作为其财产,在JavaScript中,尝试访问一个不存在的对象属性是合法的。如果历史记录不存在,则window.history返回undefined。undefined为false,因此if(undefineed){}块中的代码不会运行。
使用以下解决方案:
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假的
我仍然认为测试这两个条件的最佳/安全方法是将值转换为字符串:
var EmpName = $("div#esd-names div#name").attr('class');
// Undefined check
if (Object.prototype.toString.call(EmpName) === '[object Undefined]'){
// Do something with your code
}
// Nullcheck
if (Object.prototype.toString.call(EmpName) === '[object Null]'){
// Do something with your code
}