javascript - OPTIONAL CHAINING 和 NULLISH COALESCING 运算符的组合未呈现预期结果
问题描述
我只是在学习可选链和空值合并的组合。这里是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');
解决方案
也许从函数返回一个值,否则它有一个未定义的值:
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');
推荐阅读
- python - 使用opencv实时检测单个形状和颜色
- python - BeagleBone BLUE:如何在启动时启动磁力计
- python - 使用 psycopg2 在 Django 中保护原始 SQL 查询
- ios - 当源代码被组织到嵌套组文件夹中时,podspec 中的 source_files
- android - 有没有办法改变 Kotlin 中的三重值?
- android - 无法使用 CameraX 将捕获的图像保存到外部媒体目录
- debian - debian-policy 声明需要的目标,dh pass 可以吗?
- vb.net - 服务器响应是:即使提供了身份验证,也需要身份验证
- c++ - Linux API 和 C++ STD 向量
- python - 为什么烧瓶找不到模块flask_mysqldb?