示例 1:检查 undefined 或 null
// program to check if a variable is undefined or null
function checkVariable(variable) {
if(variable == null) {
console.log('The variable is undefined or null');
}
else {
console.log('The variable is neither undefined nor null');
}
}
let newVariable;
checkVariable(5);
checkVariable('hello');
checkVariable(null);
checkVariable(newVariable);
输出
The variable is neither undefined nor null The variable is neither undefined nor null The variable is undefined or null The variable is undefined or null
在上面的程序中,会检查一个变量是否等于null
。null
与==
一起使用会同时检查null
和undefined
值。这是因为null == undefined
的计算结果为true。
以下代码
if(variable == null) { ... }
等同于
if (variable === undefined || variable === null) { ... }
示例 2:使用 typeof
// program to check if a variable is undefined or null
function checkVariable(variable) {
if( typeof variable === 'undefined' || variable === null ) {
console.log('The variable is undefined or null');
}
else {
console.log('The variable is neither undefined nor null');
}
}
let newVariable;
checkVariable(5);
checkVariable('hello');
checkVariable(null);
checkVariable(newVariable);
输出
The variable is neither undefined nor null The variable is neither undefined nor null The variable is undefined or null The variable is undefined or null
对于undefined
值,typeof
运算符返回undefined。因此,您可以使用typeof
运算符检查undefined
值。此外,null
值使用===
运算符进行检查。
注意:我们不能对null
使用typeof
运算符,因为它返回object。
另请阅读