freecodecamp中存在如下问题:
返回由每个提供的子数组中的最大数组成的数组。 为简单起见,提供的数组将正好包含4个子数组。
记住,您可以使用简单的for循环迭代一个数组,并使用数组语法arr[i]访问每个成员。
因此,Largestofour([4,5,1,3],[13,27,18,26],[32,35,37,39],[1000,1001,857,1]);
应返回[5,27,39,1001]。
有很多方法可以完成上述任务,map()方法是最短的。 然而,我试图实现同样的使用reduce方法,但无法做到这一点。 我的方法如下。
function largestOfFour(arr) {
return arr.reduce((maxArray,item) => maxArray.push(Math.max(...item)),[]);
}
但控制台有错误,说
maxArray.push is not a function
请找到窃听器。
.push(。。。)
返回数组的新长度
,而不是数组本身,因此在第二个循环中,您要推入一个数字,而不是数组,因此您需要更改箭头函数:
const largestOfFour = arr => arr.reduce(
(max, current) => (max.push(Math.max(...current)), max),
[]
);
那会管用的。