闽公网安备 35020302035485号
在使用 JavaScript 的时候,经常需要对变量进行条件赋值,即只有当变量未定义或为 null 时,才给它赋一个默认值。这种场景在处理对象属性、函数参数等方面尤为常见。JavaScript ES2021 引入的逻辑空赋值运算符(??=)正是为了简化这种操作。本文将探讨 ??= 运算符的使用场景和优势。
variable ??= value;这等价于以下形式:
if (variable === null || variable === undefined) {
variable = value;
}
示例:使用 ??= 运算符初始化对象属性const _params = {
name: "John",
age: null,
gender: undefined,
email: "john@example.com"
};
Object.keys(_params).forEach(key => {
_params[key] ??= '';
});
const queryParams = new URLSearchParams(_params).toString();
let target = baseUrl;
if (queryParams) {
target = baseUrl.concat('?').concat(queryParams);
}
上述代码遍历 _params 对象的所有属性。对于每个属性使用 ??= 运算符检查其值是否为 null 或 undefined。如果是,将其赋值为空字符串 ''。这样,无论 age 和 gender 原本的值如何,执行完这段代码后,它们都会被初始化为一个明确的空字符串,从而避免了在使用这些属性时可能遇到的问题。
function greet(name) {
name ??= 'Guest';
console.log(`Hello, ${name}!`);
}
2. 配置对象的默认属性let appConfig = {
theme: 'dark',
notifications: undefined,
fontSize: null
};
// 确保所有配置项都有默认值
appConfig.theme ??= 'light'; // 已经有值,所以保持不变
appConfig.notifications ??= true; // 之前是 undefined,现在赋值为 true
appConfig.fontSize ??= 14; // 之前是 null,现在赋值为 14
console.log(appConfig);
// 输出:{ theme: 'dark', notifications: true, fontSize: 14 }
在这个示例中,theme 属性已经设置了值,因此 ??= 运算符不会改变它。而 notifications 和 fontSize 属性因为原来的值为 undefined 和 null,所以被赋予了新的默认值。
3. 状态管理import React, { useState } from 'react';
function UserProfile() {
const [userProfile, setUserProfile] = useState({
name: undefined,
age: null,
bio: 'No bio provided.'
});
// 模拟用户更新操作
const updateUserProfile = (name, age) => {
setUserProfile(prevState => {
const newState = {
...prevState,
name,
age,
}
newState.name ??= 'Anonymous';
newState.age ??= 18;
});
};
return (
<div>
<button onClick={updateUserProfile}>Update Profile</button>
<p>Name: {userProfile.name}</p>
<p>Age: {userProfile.age}</p>
<p>Bio: {userProfile.bio}</p>
</div>
);
}
使用 ??= 运算符来为 name 和 age 状态提供默认值,当用户点击更新按钮而这些状态未被定义时。如此一来,可以确保 userProfile 状态始终保持完整和一致,而不需要编写复杂的逻辑来检查每个值是否存在。