【问题标题】:combination of OPTIONAL CHAINING and NULLISH COALESCING operator not rendering the expected resultOPTIONAL CHAINING 和 NULLISH COALESCING 运算符的组合未呈现预期结果
【发布时间】:2021-04-13 17:38:36
【问题描述】:

我只是了解可选链空值合并的组合。 这是object

const restaurant = {
name_: 'Classico Italiano',
location: 'Via Angelo Tavanti 23, Firenze, Italy',
categories: ['Italian', 'Pizzeria', 'Vegetarian', 'Organic'],
starterMenu: ['Focaccia', 'Bruschetta', 'Garlic Bread', 'Caprese Salad'],
mainMenu: ['Pizza', 'Pasta', 'Risotto'],

openingHours: {
    thu: {
        open: 12,
        close: 22,
    },
    fri: {
        open: 11,
        close: 23,
    },
    sat: {
        open: 0, // Open 24 hours
        close: 24,
    },
},
orderPizza(ing1, ing2) {
    console.log(`you have ordered your pizza with ${ing1} and ${ing2}`);
}};

当我试图检查该方法是否存在时,它无论如何都会打印出它们。我做错了什么?

console.log(restaurant.orderPizza?.('some', 'something') ?? 'no method exist');

【问题讨论】:

  • 你喜欢打印什么?
  • 你得到什么确切,你期待什么确切
  • 我得到了这两个值,而我应该只得到第一个,如果它存在或最后一个,'不存在方法',如果它不存在。

标签: javascript methods optional-chaining nullish-coalescing


【解决方案1】:

也许从函数返回一个值,否则它有一个未定义的值:

const restaurant1 = {
  name_: 'Classico Italiano',
  orderPizza(ing1, ing2) {
    return `you have ordered your pizza with ${ing1} and ${ing2}`;
  }
};

const restaurant2 = {
  name_: 'Other',
};

console.log(restaurant1.orderPizza?.('some', 'something') ?? 'no method exist');
console.log(restaurant2.orderPizza?.('some', 'something') ?? 'no method exist');

【讨论】:

  • 是的,这解决了问题。但你看到在另一种情况下,登录控制台工作正常。
  • @Nafi 不管怎样,你能不能从函数中返回一个非未定义或空值?
猜你喜欢
  • 2020-03-07
  • 2021-09-27
  • 2012-02-12
  • 1970-01-01
  • 2021-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多