数据结构测试问题: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
相关产品推荐
相关产品推荐

