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

为何执行JavaScript对象遍历代码时出现ReferenceError而非预期输出?

遍历对象时ReferenceError错误的解决方法及代码优化

错误原因

你遇到的ReferenceError: object is not defined是因为代码里错误使用了小写的object——JavaScript中获取对象键的正确方法是大写开头的Object.keys(),Object是JS内置的全局构造函数,小写的object是未声明的变量,自然会触发报错。

另外你的代码还有两个细节问题:

  • 字符串拼接缺少空格,会导致输出内容连在一起(比如marks of harryare44),不符合预期格式
  • 循环中重复调用Object.keys(marks),没必要且影响运行效率

修正后的代码

方式1:修复原始for循环

先把对象键数组存起来,再用模板字符串控制输出格式:

let marks = {
  harry: 44,
  shg: 544,
  ccc: 44,
  gugugu: 99
};
// 提前获取所有键,避免重复计算
const studentNames = Object.keys(marks);
for (let i = 0; i < studentNames.length; i++) {
  const name = studentNames[i];
  console.log(`marks of ${name} are ${marks[name]}`);
}

方式2:更简洁的for...of遍历

直接遍历键数组,写法更清晰直观:

let marks = {
  harry: 44,
  shg: 544,
  ccc: 44,
  gugugu: 99
};
for (const name of Object.keys(marks)) {
  console.log(`marks of ${name} are ${marks[name]}`);
}

方式3:for...in遍历(需过滤继承属性)

如果使用for...in,记得加上hasOwnProperty检查,避免遍历到对象继承的无关属性:

let marks = {
  harry: 44,
  shg: 544,
  ccc: 44,
  gugugu: 99
};
for (const name in marks) {
  // 确保只遍历对象自身的属性
  if (marks.hasOwnProperty(name)) {
    console.log(`marks of ${name} are ${marks[name]}`);
  }
}

运行结果

以上代码都会输出符合预期的内容:

marks of harry are 44
marks of shg are 544
marks of ccc are 44
marks of gugugu are 99

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 20:43:52