如何确定变量是未定义的还是空的?
我的代码如下:
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解释器将停止执行。
当前回答
var i;
if (i === null || typeof i === 'undefined') {
console.log(i, 'i is undefined or null')
}
else {
console.log(i, 'i has some value')
}
其他回答
编辑后的答案:在我看来,你不应该使用我下面的旧答案中的函数。相反,您应该知道变量的类型,并直接使用根据检查(例如,想知道数组是否为空?只需执行if(arr.length==0){}等)。这个答案甚至不能回答OP的问题。
我来编写自己的函数。JavaScript很奇怪。
它几乎可以用于任何事情。(注意,这也会检查变量是否包含任何可用值。但由于通常也需要这些信息,我认为值得发布)。请考虑留下一张纸条。
function empty(v) {
let type = typeof v;
if (type === 'undefined') {
return true;
}
if (type === 'boolean') {
return !v;
}
if (v === null) {
return true;
}
if (v === undefined) {
return true;
}
if (v instanceof Array) {
if (v.length < 1) {
return true;
}
} else if (type === 'string') {
if (v.length < 1) {
return true;
}
if (v === '0') {
return true;
}
} else if (type === 'object') {
if (Object.keys(v).length < 1) {
return true;
}
} else if (type === 'number') {
if (v === 0) {
return true;
}
}
return false;
}
TypeScript兼容。
该函数应该执行与PHP的empty()函数完全相同的操作(请参见RETURN VALUES)
将undefined、null、false、0、0.0、“0”{}、[]视为空。
“0.0”、NaN、“”、true被视为非空。
我在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
(null == undefined) // true
(null === undefined) // false
因为==检查类型和值。两者的类型不同,但值相同。
让我们看看这个,
让苹果;//只将变量声明为apple警报(苹果);//未定义在上文中,变量仅声明为apple。在这种情况下,如果我们调用方法alert,它将显示undefined。 让apple=null;/*将变量声明为apple并初始化,但值为空*/警报(苹果);//无效的
第二个显示为空,因为apple值的变量为空。
因此,您可以检查值是未定义的还是空的。
if(apple !== undefined || apple !== null) {
// Can use variable without any error
}
jQueryattr()函数返回一个空字符串或实际值(绝对不能为空或未定义)。它返回undefined的唯一时间是选择器没有返回任何元素。
因此,您可能需要针对空白字符串进行测试。或者,由于空字符串、null和undefined为false-y,您可以这样做:
if (!EmpName) { //do something }