是否存在反向逻辑无效分配?

Is there a reverse logical nullish assignment?

因此 ??= 运算符仅在当前存储的值为空值时才将值赋给变量。

也许我遗漏了显而易见的东西,但我想不出一个巧妙的解决方案(没有 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;

您可以使用 logical AND assignment.

来自 MDN 网络文档:

let a = 1;
let b = 0;

a &&= 2;
console.log(a);
// expected output: 2

b &&= 2;
console.log(b);
// expected output: 0

澄清后添加另一个答案,因为编辑我之前的答案似乎很奇怪。

我能想到的没有 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;