如何判断变量是undefined
还是null
?
我的代码如下:
var EmpName = $("div#esd-names div#name").attr('class');
if(EmpName == 'undefined'){
// DO SOMETHING
};
<div id="esd-names">
<div id="name"></div>
</div>
但是当我这样做时,JavaScript解释器会停止执行。
如何判断变量是undefined
还是null
?
我的代码如下:
var EmpName = $("div#esd-names div#name").attr('class');
if(EmpName == 'undefined'){
// DO SOMETHING
};
<div id="esd-names">
<div id="name"></div>
</div>
但是当我这样做时,JavaScript解释器会停止执行。
我在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或未定义。
if(typeof sVal === 'undefined' || sVal === null || sVal === ''){
console.log('variable is undefined or null');
}
typeof
直接与 undefined
进行比较,而不是将其作为字符串。这样可以工作,但额外的运算符只会使它变得啰嗦。 - temporary_user_name(null == undefined) // true
(null === undefined) // false
因为 === 检查类型和值。虽然两个类型不同,但值相同。
foo == null
检查应该能够以最短的方式解决“未定义或空值”的情况。(不考虑“foo未声明”的情况。)但是,习惯使用3个等号(作为最佳实践)的人可能不会接受它。只需查看 eslint 和 tslint 中的 eqeqeq 或 triple-equals 规则即可了解情况...
在这种情况下,应该采用显式方法,即分别检查变量是否为 undefined
或 null
,而我对这个主题的贡献(目前有27个非负答案!)是使用 void 0
作为既简短又安全的方法来执行对 undefined
的检查。
foo === undefined
不安全,因为undefined不是保留字并且可能被屏蔽(MDN)。使用typeof === 'undefined'
检查是安全的,但如果我们不关心foo未声明的情况,则可以使用以下方法:if (foo === void 0 || foo === null) { ... }
让我们来看一下这个:
let apple; // Only declare the variable as apple
alert(apple); // undefined
In the above, the variable is only declared as apple
. In this case, if we call method alert
it will display undefined.
let apple = null; /* Declare the variable as apple and initialized but the value is null */
alert(apple); // null
apple
的值是 null。if(apple !== undefined || apple !== null) {
// Can use variable without any error
}
我认为你可以这样做,这样在一个条件语句中检查同一变量的多个值会更有效率。
const x = undefined;
const y = null;
const z = 'test';
if ([undefined, null].includes(x)) {
// Will return true
}
if ([undefined, null].includes(y)) {
// Will return true
}
if ([undefined, null].includes(z)) {
// Will return false
}
如果您喜欢沿用 ===
运算符并且希望代码更加明确,您也可以使用 (value ?? null) === null
。
到目前为止,有三种方法。
value == null
value === null || value === undefined
(value ?? null) === null
我通常避免使用==
,但这次我更喜欢== null
。
Symbol()
呢❓ 为什么不直接使用 (a ?? null) === null
❓ 或者 (a ?? undefined) === undefined
❓ - noseratio - open to workvar x;
if (x === undefined) {
alert ("only declared, but not defined.")
};
if (typeof y === "undefined") {
alert ("not even declared.")
};
你只能使用第二个:因为它将检查定义和声明两者
var i;
if (i === null || typeof i === 'undefined') {
console.log(i, 'i is undefined or null')
}
else {
console.log(i, 'i has some value')
}
typeof
永远不会产生 undefined
,只会产生字符串 'undefined'
。此外,如果 i
是 undefined
,则 i == null
已经为真,因此即使第二个布尔值有效,它也会变得多余。 - temporary_user_name