示例 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 运算符,因为它返回对象。