因此,??=
仅当当前存储的值为空值时,运算符才将值分配给变量。
也许我错过了显而易见的事情,但我想不出一个巧妙的解决方案(没有 if 语句)仅在值不为 null 的情况下分配?
我正在使用 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