假设我们有一个对象数组,其中包含有关测试中某些学生的分数的信息-
const students = [ { name: 'Andy', total: 40 }, { name: 'Seric', total: 50 }, { name: 'Stephen', total: 85 }, { name: 'David', total: 30 }, { name: 'Phil', total: 40 }, { name: 'Eric', total: 82 }, { name: 'Cameron', total: 30 }, { name: 'Geoff', total: 30 } ];
我们需要编写一个JavaScript函数,该函数接受一个这样的数组并返回一个对象,该对象的名称和total的值对于total而言是最高的。
因此,对于上述数组,输出应为-
{ name: 'Stephen', total: 85 }
以下是代码-
const students = [ { name: 'Andy', total: 40 }, { name: 'Seric', total: 50 }, { name: 'Stephen', total: 85 }, { name: 'David', total: 30 }, { name: 'Phil', total: 40 }, { name: 'Eric', total: 82 }, { name: 'Cameron', total: 30 }, { name: 'Geoff', total: 30 } ]; const pickHighest = arr => { const res = { name: '', total: -Infinity }; arr.forEach(el => { const { name, total } = el; if(total > res.total){ res.name = name; res.total = total; }; }); return res; }; console.log(pickHighest(students));
输出结果
这将在控制台上产生以下输出-
{ name: 'Stephen', total: 85 }