因此,仅当当前存储的值为空值时,空值合并赋值运算符
??=
才会将值分配给变量。
也许我错过了显而易见的事情,但我想不出一个巧妙的解决方案(没有if语句)来仅分配如果所分配的右侧值不为空?
我正在使用nodeJS来提供更多上下文。
我想要
let x r??= 2;
// Updates 'x' to hold this new value
x r??= undefined;
// Has no effect, since the value to assign is nullish
console.log(x); // 2
编辑 为了更清楚地说明我的问题:
我只想为变量分配一个新值,如果该新值不为空。
let iceCream = {
flavor: 'chocolate'
}
const foo = 2.5
const bar = undefined;
iceCream.price r??= bar
// does not assign the new value because it is nullish
console.log(iceCream.price) // expected to be error, no such property
iceCream.price r??= foo
// assigns the new value because it is not nullish but a float
console.log(iceCream.price) // expected to be 2.5
iceCream.price r??= bar
// does not assign the new value because it is nullish
console.log(iceCream.price) // expected to still be 2.5
不,那不是单个操作员。最接近的是两个运算符:
x = undefined ?? x;
在编辑我之前的答案后添加另一个答案似乎很奇怪。
我能想到的不使用 if 的解决方案的最简单方法如下:
let iceCream = {
flavor: 'chocolate'
}
const foo = 2.5
const bar = undefined;
bar && (iceCream.price = bar)
// Another possible solution if creating the property with a nullish value is ok for you:
iceCream.price = bar || iceCream.price;
您可以使用逻辑与赋值。
来自 MDN Web 文档:
let a = 1;
let b = 0;
a &&= 2;
console.log(a);
// expected output: 2
b &&= 2;
console.log(b);
// expected output: 0