You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 20:12:35