JS 判断 undefined 和 null
在 JavaScript 中, undefined 和 null 都表示没有值,但两者有区别。undefined 表示尚未定义;null 表示已定义但为空。判断未定义和空值是 JavaScript 开发的常见操作之一,下面将从多个角度分析如何判断 undefined 和 null。
1. 使用 typeof 操作符
typeof 操作符可返回操作数的数据类型。当操作数未定义时,返回 "undefined";当操作数为空时,返回 "object"。因此,使用 typeof 操作符可判断一个变量是否为 undefined 或 null。
如下是一个示例代码:
```
let x;
console.log(typeof x); // output: "undefined"
let y = null;
console.log(typeof y); // output: "object"
```
2. 使用严格相等运算符
严格相等运算符(===)可判断值和数据类型是否相等。使用严格相等运算符判断 undefined 和 null,因为它们的数据类型不同,所以需要分别判断。
如下是一个示例代码:
```
let x;
if (x === undefined) {
console.log("x is undefined");
}
let y = null;
if (y === null) {
console.log("y is null");
}
```
3. 使用 typeof 和严格相等运算符
结合使用 typeof 和严格相等运算符可以更精确地判断变量的状态。
如下是一个示例代码:
```
let x;
if (typeof x === "undefined") {
console.log("x is undefined");
}
let y = null;
if (y === null) {
console.log("y is null");
}
```
4. 使用 nullish coalescing 运算符
nullish coalescing 运算符(??)用于判断一个变量是否为 null 或 undefined。如果变量为 null 或 undefined,则返回默认值。
如下是一个示例代码:
```
let x = null;
let y = x ?? "default value";
console.log(y); // output: "default value"
```
5. 使用 Optional chaining 运算符
Optional chaining 运算符(?.)用于判断变量是否为 null 或 undefined,并且在访问变量的属性或方法时避免出现错误。
如下是一个示例代码:
```
let obj = {
property: {
method: function() {
console.log("Hello");
}
}
};
// 判断对象和属性是否存在,并调用方法
obj?.property?.method(); // output: "Hello"
let emptyObj = {};
// 判断对象和属性是否存在,并调用方法
emptyObj?.property?.method(); // output: undefined
```
结论
本文从使用 typeof 操作符、严格相等运算符、nullish coalescing 运算符和 Optional chaining 运算符等角度分析了如何判断 undefined 和 null。了解如何判断变量状态可以帮助开发人员编写更健壮的代码。
微信扫一扫,领取最新备考资料