如何在TypeScript中检查菜单对象数组是否包含指定菜品名称
解决方案
先纠正两个小问题:
- 你的
menu是同步数组,不需要用await menu[index],直接取值即可 - 遍历数组更推荐用
for...of而非for...in,后者主要用于遍历对象属性,遍历数组可能会拿到非索引的额外属性
要检查餐厅菜品中是否存在fried rice,可以用数组的some()方法——它会遍历数组,只要找到至少一个满足条件的元素就停止遍历并返回true,效率较高。
修改后的完整代码如下:
for (const restaurant of menu) { // 检查当前餐厅的菜品里是否有'fried rice' const hasFriedRice = restaurant.dish.some(dishItem => dishItem.name === 'fried rice'); if (hasFriedRice) { // 执行你需要的操作 console.log(`餐厅 ${restaurant.restaurant} 提供 fried rice`); } }
补充说明
如果需要忽略大小写匹配(比如兼容Fried Rice这类写法),可以把判断逻辑改成:
const hasFriedRice = restaurant.dish.some(dishItem => dishItem.name.toLowerCase() === 'fried rice' );
内容的提问来源于stack exchange,提问作者user3083590
相关产品推荐
相关产品推荐

