【发布时间】:2022-01-03 05:33:45
【问题描述】:
因此,??= 运算符仅在当前存储的值为空值时才将值分配给变量。
也许我错过了显而易见的事情,但我想不出一个巧妙的解决方案(没有 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不是已经这样做了吗? -
@Ivar
x ?? = undefined如果x为空,则将x分配给 undefined。如果x不为空,OP 想要分配。 -
@Proxycon:为了清晰和最合适的替代方案,显示您将要使用它的上下文?
-
据我了解(并且我认为 Ry 指的是),如果右侧操作符不是无效的(而不是当 @ 987654330@ 不是无效的)。虽然我最初的评论不起作用,因为如果两个值都不为空(如果
x是2并且您使用x ??= 3,它将保持2而不是分配3)。 -
关于“预期是错误,没有这样的属性”,请注意访问对象的不存在属性不会引发错误。它只是返回未定义。 (但访问
undefined值/属性的属性会引发错误。)
标签: javascript conditional-operator assignment-operator nullish-coalescing