【问题标题】:Both the sides of nullish coalescing operator in JavaScript are being executedJavaScript 中空值合并运算符的两边都在执行
【发布时间】:2021-06-02 17:54:18
【问题描述】:
console.log(restaurant.orderPizza?.('onion','tomato','basil') ?? 'Method does not exist');

console.log(restaurant.orderRissotto?.('onion','tomato','basil') ?? 'Method does not exist'

orderPizzaorderRissotto 是对象 restaurant 中的两个方法。

当我使用 Nullish Coalesceing 运算符记录它们时,方法输出会被记录,因为方法可用。但是,第二部分 '方法不存在' 也会被记录。可能是什么原因?

日志:

Your pizza with onion, tomato and basil is ready
Method does not exist

【问题讨论】:

  • 也许 orderRissotto 方法返回 null 或未定义?
  • @adiga 说了什么...

标签: javascript methods nullish-coalescing


【解决方案1】:

Null Safe 返回null,如果第一个是null || undefinedNullish coalescing 运算符将返回第二个...因此,如果您的方法不存在,则 null 保险箱将返回 null,并且因此将返回第二部分,但如果方法存在但返回 null || undefined 值,则将运行第一部分,但将打印第二部分(因为您的方法返回 Nullish coalescing 用于确定的值之一如果第二部分应该返回)

【讨论】:

    【解决方案2】:

    let restaurant = {
      orderPizza: function(arg1, arg2, arg3) {
        return `Your pizza with ${arg1}, ${arg2} and ${arg3} is ready`
      },
      orderRisotto: function(arg1, arg2, arg3) {
        return `Your risotto with ${arg1}, ${arg2} and ${arg3} is ready`
      }
    }
    
    
    console.log(restaurant.orderPizza?.('onion', 'tomato', 'basil') ?? "Method not found");
    
    console.log(restaurant.orderRisotto?.('onion', 'tomato', 'basil')) ?? "Method not found";

    尝试在我的本地机器上执行上面的代码sn-p,我能够按预期正确执行它。

    注意:这两个 console.log 语句是不同的。

    如果您尝试在开发工具控制台中执行这些命令,结果会有所不同。

    对于第一个 console.log 语句 -

    console.log(restaurant.orderPizza?.('onion', 'tomato', 'basil') ?? "Method not found");
    

    结果将符合预期,因为字符串是从 orderPizza 方法返回的,并且 Nullish 合并运算符的表达式左侧不是 null 或未定义。因此控制台打印 -

    Your pizza with onion, tomato and basil is ready
    

    但是对于第二个 console.log 语句 -

    console.log(restaurant.orderRisotto?.('onion', 'tomato', 'basil')) ?? "Method not found";
    

    注意 console.log 的右括号。该语句将打印 -

    Your risotto with onion, tomato and basil is ready
    "Method not found"
    

    orderRisotto 方法按预期工作并生成字符串,然后将其传递给控制台的 log 方法。但是由于 log 方法是一个 void 方法,它返回 undefined,这使得左侧 Nullish 合并运算符未定义,因此右侧也被评估。

    我希望这个答案会有所帮助。

    【讨论】:

      猜你喜欢
      • 2018-05-24
      • 1970-01-01
      • 2010-10-03
      • 1970-01-01
      • 2021-08-29
      • 2011-11-08
      • 2021-04-20
      • 2017-09-04
      相关资源
      最近更新 更多