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

数据结构测试问题:JS使用for-in遍历gamerScores对象错误排查

代码问题说明
  • 遍历逻辑不匹配:你使用了针对数组的普通索引for循环,但gamerScores是普通对象,不存在length属性,循环判定条件i < gamerScores.length永远为假,循环体不会执行
  • 取值方式错误:普通对象的键为字符串类型的玩家名,不是数字索引,即便循环执行,用gamerScores[i]也无法获取到对应值
  • 不符合题目要求:题目明确要求使用for-in循环实现,当前实现未满足该要求
正确实现
let gamerScores = {
  john: 89,
  paul: 725,
  george: 553,
  robert: 9302,
  steve: 733,
};

// 使用for-in遍历对象
for (let gamerName in gamerScores) {
  // 输出键(玩家名)和对应的值(分数)
  console.log('玩家:' + gamerName + ',分数:' + gamerScores[gamerName]);
}

可选优化:如果需要避免遍历到对象原型链上继承的可枚举属性,可以增加hasOwnProperty校验:

for (let gamerName in gamerScores) {
  if (gamerScores.hasOwnProperty(gamerName)) {
    console.log('玩家:' + gamerName + ',分数:' + gamerScores[gamerName]);
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 09:12:01