相信大部分前端工程师都遇到过读取一个undefined或null值身上的属性导致报错的情况,下面来介绍ES6一些新的语法来方便我们开发。
?.、?? 和 ??= 是一些新的语法糖,它们为开发者提供了更便利和安全的方式来处理变量的赋值和检查,特别是在处理可能存在 null 或 undefined 的情况下。让我们逐个来看这些语法的用法和使用场景。
1、 ?.(可选链操作符)
可选链操作符 ?. 是 ECMAScript 2020 新增的语法,用于简化访问可能为 null 或 undefined 的对象属性的过程,避免了因为空值而导致的错误。
用法示例:
const user = {
name: 'John',
address: {
city: 'New York'
}
};
// 使用可选链操作符
const cityName = user.address?.city;
console.log(cityName); // 输出: 'New York'
const undefinedUser = undefined;
const city = undefinedUser?.address?.city;
console.log(city); // 输出: undefined,避免报错
// 传统写法
const city = undefinedUser&& undefinedUser.address&& undefinedUser.address.city; // 需要手动检查每个属性
2、 ??(空值合并操作符)
空值合并操作符 ?? 用于在变量为 null 或 undefined 时提供一个默认值。
用法示例:
const someValue = null;
const defaultValue = 'Hello';
// 使用空值合并操作符
const result = someValue ?? defaultValue;
console.log(result); // 输出: 'Hello'
const anotherValue = undefined;
const result2 = anotherValue ?? 'World';
console.log(result2); // 输出: 'World'
//可能存在的传统写法,除了null,undefined, 无法兼容0、''、false的情况,使用时要特别小心
const value1 = null || 'default'; // 'default'
const value3 = 0 || 'default'; // 'default',因为 0 转布尔类型是 false
const value4 = '' || 'default'; // 'default',因为 '' 转布尔类型是 false
3、. ??=(空值合并赋值操作符)
空值合并赋值操作符 ??= 用于在变量为 null 或 undefined 时,将给定的默认值赋给该变量。
用法示例:
let value = null;
value ??= 'default';
console.log(value); // 输出: 'default'
let anotherValue = 'hello';
anotherValue ??= 'default';
console.log(anotherValue); // 输出: 'hello',因为变量已定义不为 null 或 undefined
使用场景
表单处理当处理用户输入时,经常需要检查输入的值是否为 null 或 undefined,这时候可以使用 ?? 来提供默认值,或者使用 ?. 来安全地访问嵌套属性。
API 调用在从后端 API 获取数据时,可能会遇到数据缺失的情况,这时候可以使用 ?. 来避免因为 null 或 undefined 导致的异常。
状态初始化在初始化变量或状态时,使用 ?? 来确保变量有一个合理的默认值,而不是 null 或 undefined。
总结
这些运算符在处理可能为 null 或 undefined 的值时非常有用,可以简化代码并提高可读性。然而,需要注意的是,它们是在 ECMAScript 2020 标准中引入的,因此在旧版本的 JavaScript 中可能不被支持。