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

如何修改JS代码,仅遍历完menuItem无匹配产品时输出提示?

修改方案

问题出在你把错误提示放在了循环的else分支里,导致每遍历到一个不匹配的菜品就会输出一次提示。要实现仅在全部遍历完成且无匹配项时才提示错误,你可以这样修改:

方法一:用标记变量追踪匹配状态

let menuItem = {
  item_1: {
    name: "french burger",
    price: 1000,
    productCode: 101
  },
  item_2: {
    name: "chicken sharwama",
    price: 1500,
    productCode: 102
  },
  item_3: {
    name: "pizza",
    price: 5000,
    productCode: 103
  },
  item_4: {
    name: "beef sharwama",
    price: 1500,
    productCode: 104
  },
  item_5: {
    name: "smoothie (mix flavor)",
    price: 1300,
    productCode: 105
  }
}

listMenuItem = () => {
  for (let i in menuItem) {
    console.log(`Order Code: ${menuItem[i].productCode} || ${menuItem[i].name},  ${menuItem[i].price} NGN \n`)
  }
}

listMenuItem()
var order = prompt("Enter product code to make your order: ")
console.log(order)
let customerOrder = []
// 添加标记变量,默认未找到
let found = false

for (let i in menuItem) {
  if (menuItem[i].productCode == order) {
    customerOrder.push(menuItem[i])
    console.log(customerOrder)
    console.log(`${menuItem[i].name},  ${menuItem[i].price}`)
    // 找到匹配项,标记为true
    found = true
    // 找到后直接跳出循环,无需继续遍历
    break
  }
}

// 循环结束后检查标记,未找到则输出提示
if (!found) {
  console.log("Product does not exist, try again")
}

方法二:利用customerOrder数组长度判断

因为找到匹配项时会把菜品对象push到customerOrder里,所以循环结束后只要判断数组长度是否为0即可:

// ... 前面代码不变 ...

for (let i in menuItem) {
  if (menuItem[i].productCode == order) {
    customerOrder.push(menuItem[i])
    console.log(customerOrder)
    console.log(`${menuItem[i].name},  ${menuItem[i].price}`)
    break // 找到后停止遍历,优化性能
  }
}

// 数组为空说明没找到匹配项
if (customerOrder.length === 0) {
  console.log("Product does not exist, try again")
}

关键改动说明

  • 移除了循环内部的else分支,避免重复输出错误提示
  • 添加break语句:找到匹配项后立即终止循环,不需要继续遍历剩余菜品,提升效率
  • 将错误提示逻辑移到循环外部,仅在确认没有任何匹配项时才执行

内容的提问来源于stack exchange,提问作者Donatus Prince

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 18:40:39