因此,只有当当前存储的值为零时,??=
运算符才会将值分配给变量。
也许我错过了显而易见的东西,但我想不出一个巧妙的解决方案(没有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
不,这不是一个单独的运算符。最接近的是两个运营商:
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;
您可以使用逻辑AND赋值。
来自MDN Web文档:
let a = 1;
let b = 0;
a &&= 2;
console.log(a);
// expected output: 2
b &&= 2;
console.log(b);
// expected output: 0