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

遍历restaurant嵌套staff并添加名称到数组报错求助

问题排查:for-in循环未声明key变量引发的报错

你遇到的报错'Use a declaration keyword when declaring your key variable',核心问题出在for-in循环里的key变量没有用声明关键字(let/const)定义。

看你提供的代码:

const restaurant = {
  tables: 32,
  staff: {
    chef: "Andy",
    waiter: "Bob",
    manager: "Charlie"
  },
  cuisine: "Italian",
  isOpen: true
};

const staffNames = []

for (key in restaurant.staff){
  const value = restaurant.staff[key]
  staffNames.push(value)
}

这里的key没有用let或const声明,在严格模式下,这种隐式创建全局变量的写法会直接触发报错——JS引擎判定你遗漏了变量声明关键字。

修复方案

只需要在for循环的括号里给key加上const或者let即可:

const restaurant = {
  tables: 32,
  staff: {
    chef: "Andy",
    waiter: "Bob",
    manager: "Charlie"
  },
  cuisine: "Italian",
  isOpen: true
};

const staffNames = []

// 给key添加const声明
for (const key in restaurant.staff){
  const value = restaurant.staff[key]
  staffNames.push(value)
}

// 也可以用更简洁的写法直接获取所有值
// const staffNames = Object.values(restaurant.staff);

添加声明关键字后,key的作用域被限制在循环内部,既符合语法规范,也避免了意外的全局变量污染。另外用Object.values()方法可以一步获取staff对象的所有属性值,写法更简洁高效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 03:36:58