【问题标题】:Is there a reverse logical nullish assignment?是否存在反向逻辑无效赋值?
【发布时间】: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@ 不是无效的)。虽然我最初的评论不起作用,因为如果两个值都不为空(如果x2 并且您使用x ??= 3,它将保持2 而不是分配3)。
  • 关于“预期是错误,没有这样的属性”,请注意访问对象的不存在属性不会引发错误。它只是返回未定义。 (但访问 undefined 值/属性的属性会引发错误。)

标签: javascript conditional-operator assignment-operator nullish-coalescing


【解决方案1】:

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

我能想到的不使用 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;

【讨论】:

    【解决方案2】:

    你可以使用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
    

    【讨论】:

    • 但是这个运算符也只取决于存储在变量中的值,而不是如果我理解正确的话要分配的值。
    【解决方案3】:

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

    x = undefined ?? x;
    

    【讨论】:

    • 这很接近,但如果我想在对象上设置新属性,它不起作用。
    • @Proxycon:那么,您需要一个 if 或一个包装函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-22
    • 2011-05-25
    • 1970-01-01
    • 2018-06-24
    相关资源
    最近更新 更多