【发布时间】:2020-03-05 03:09:15
【问题描述】:
首先,我的功能需要一个示例。一个学生数组被传递给该函数,该函数返回一个数组,其中每个学生的最高分作为项目。
getStudentTopScores([
{
id: 1,
name: "Jacek",
scores: [5, 3, 4, 2, 5, 5]
},
{
id: 2,
name: "Ewa",
scores: [2, 3, 3, 3, 2, 5]
},
{
id: 3,
name: "Zygmunt",
scores: [2, 2, 4, 4, 3, 3]
}
]) ➞ [5, 5, 4]
以下是我的工作功能。我需要一些帮助来解释它的工作原理。
const getStudentTopScores=students=>
students
.map(student=>student.scores)
.reduce((arr,scores)=>{
const score = scores.length?Math.max(...scores):0;
arr.push(score);
return arr;
},[]);
那么,我的代码是怎么回事?
- 一组学生被传递给函数getStudentTopScores
-
.map() 方法应用于数组:
.map(student=>student.scores) 我认为这是访问存储在学生内部的 scores 数组。
-
.reduce() 方法应用于每个score。这会获取每个分数并询问:这个分数是数组中的最高分数吗?如果答案是肯定的,那么该值存储在 score 中,如果答案是否定的, 然后 0 存储在 score 中。
score 中存储的值被添加到累加器 (arr)。
该值是特定学生的最高分。 如果有多个相同且最大的分数怎么办?为什么不将这些全部添加到累加器中,创建一个值,该值是该个人所有最高分的总和?
该代码仅适用于最后的空数组。我不知道为什么需要这样做。请解释一下。
【问题讨论】:
-
是关于
reduce中的[]的问题吗?是累加器的intialValue:
标签: javascript arrays reduce