JavaScript如何从对象数组中获取最高的score数值?
代码问题排查与修复
核心错误原因
- 打印语句位置错误:你将
console.log(best_result)放在了if条件判断的内部,只要遍历到分数高于当前记录最高分的学生,就会触发一次打印。第一次遍历到分数88的学生时触发打印,后续遍历到分数98的学生时再次触发打印,因此会输出两个结果。 - 最高分变量未初始化:
best_result声明时没有赋值,默认值为undefined,数字与undefined做大小比较时结果恒为false,若出现所有学生分数为负的场景,逻辑会完全失效。
修复后的代码
方案1:修改原有循环逻辑
const classInfo = { students: [ { firstName: "Joe", lastName: "Smith", score: 88 }, { firstName: "John", lastName: "Doe", score: 65 }, { firstName: "Joel", lastName: "Garcia", score: 98 }, { firstName: "Judy", lastName: "Johnson", score: 77 }, { firstName: "Anne", lastName: "Dew", score: 88 }, ] }; // 初始化最高分设为负无穷,保证所有正常分数都能覆盖 let best_result = -Infinity; for (let i = 0; i < classInfo.students.length; i++) { if (classInfo.students[i].score > best_result) { best_result = classInfo.students[i].score; } } // 循环结束统一打印最终最高分 console.log(best_result);
运行后只会输出最终最高分98。
方案2:更简洁的内置方法实现
用Array.map提取所有分数,再用Math.max取最大值即可:
const bestResult = Math.max(...classInfo.students.map(item => item.score)) console.log(bestResult)
内容的提问来源于stack exchange,提问作者QuanN
相关产品推荐
相关产品推荐

