试一试
const a = { duration: 50 };
a.speed ??= 25;
console.log(a.speed);
// Expected output: 25
a.duration ??= 10;
console.log(a.duration);
// Expected output: 50
语法
js
x ??= y
描述
空值合并赋值具有短路特性,这意味着 x ??= y 等同于 x ?? (x = y),不同之处在于表达式 x 只会评估一次。
如果左侧不为空值,则由于空值合并运算符的短路特性,不会执行赋值。例如,以下代码不会抛出错误,即使 x 是 const
js
const x = 1;
x ??= 2;
以下代码也不会触发 setter
js
const x = {
get value() {
return 1;
},
set value(v) {
console.log("Setter called");
},
};
x.value ??= 2;
事实上,如果 x 不为空值,则根本不会评估 y。
js
const x = 1;
x ??= console.log("y evaluated");
// Logs nothing
示例
使用空值合并赋值
您可以使用空值合并赋值运算符为对象属性应用默认值。与使用解构和默认值相比,如果属性的值为 null,??= 也会应用默认值。
js
function config(options) {
options.duration ??= 100;
options.speed ??= 25;
return options;
}
config({ duration: 125 }); // { duration: 125, speed: 25 }
config({}); // { duration: 100, speed: 25 }
规范
| 规范 |
|---|
| ECMAScript® 2026 语言规范 # sec-assignment-operators |
浏览器兼容性
加载中…