0

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

也许我错过了显而易见的事情,但我想不出一个巧妙的解决方案(没有 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
4

3 回答 3

2

不,这不是一个单一的运营商。最接近的是两个运算符:

x = undefined ?? x;
于 2021-11-24T20:47:44.043 回答
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;
于 2021-11-25T00:31:05.450 回答
-1

您可以使用逻辑 AND 分配

来自 MDN 网络文档:

let a = 1;
let b = 0;

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

b &&= 2;
console.log(b);
// expected output: 0
于 2021-11-24T20:47:53.000 回答