示例 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。
另请阅读