跳到主要内容

JavaScript 程序:检查变量是否为 undefined 或 null

要理解这个示例,你应该具备以下 JavaScript 编程 主题的知识:

示例 1:检查 undefined 或 null

// 程序检查变量是否为 undefined 或 null

function checkVariable(variable) {
if (variable == null) {
console.log("变量为 undefined 或 null");
} else {
console.log("变量既不是 undefined 也不是 null");
}
}

let newVariable;

checkVariable(5);
checkVariable("hello");
checkVariable(null);
checkVariable(newVariable);

输出

变量既不是 undefined 也不是 null
变量既不是 undefined 也不是 null
变量为 undefinednull
变量为 undefinednull

在上述程序中,检查了变量是否等同于 null。使用 == 检查 null 可以同时检测 nullundefined 值。这是因为 null == undefined 计算结果为真。

以下代码:

if(variable == null) { ... }

等同于

if (variable === undefined || variable === null) { ... }

示例 2:使用 typeof

// 程序检查变量是否为 undefined 或 null

function checkVariable(variable) {
if (typeof variable === "undefined" || variable === null) {
console.log("变量为 undefined 或 null");
} else {
console.log("变量既不是 undefined 也不是 null");
}
}

let newVariable;

checkVariable(5);
checkVariable("hello");
checkVariable(null);
checkVariable(newVariable);

输出

变量既不是 undefined 也不是 null
变量既不是 undefined 也不是 null
变量为 undefinednull
变量为 undefinednull

typeof 运算符对于 undefined 值返回 undefined。因此,你可以使用 typeof 运算符检查 undefined 值。此外,使用 === 运算符检查 null 值。

注意:我们不能对 null 使用 typeof 运算符,因为它返回 object。