JavaScript 中 null 合并运算符的两边都在执行

问题描述

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

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

orderPizzaorderRissottorestaurant 对象内部的两个方法

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

日志:

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

解决方法

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

,

let restaurant = {
  orderPizza: function(arg1,arg2,arg3) {
    return `Your pizza with ${arg1},${arg2} and ${arg3} is ready`
  },orderRisotto: function(arg1,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','basil')) ?? "Method not found";

尝试在我的本地机器上执行上述代码片段,我能够按预期正确执行它。

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

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

对于第一个 console.log 语句 -

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

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

Your pizza with onion,tomato and basil is ready

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

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

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

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

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

希望这个回答有帮助。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...