gpt4 book ai didi

javascript - 在数组数组的 map() 中使用 reduce()

转载 作者:行者123 更新时间:2023-12-03 16:26:29 25 4
gpt4 key购买 nike

我正在参加 freecodecamp 挑战,想知道为什么我的代码不起作用以及如何更正它。

目标是“返回一个数组,该数组由每个提供的子数组中的最大数组成。”

我的尝试是使用 reduce 作为映射函数来映射输入数组:

function largestOfFour(arr) {
arr = arr.map(function(innerArray){
innerArray = innerArray.reduce(function(previousValue,currentValue){
return currentValue > previousValue ? currentValue : previousValue;
});
});
return arr;
}

console.log(largestOfFour([[4, 5, 1, 3],[1, 2, 3, 4]]));

当前输出为:[undefined, undefined]

我应该如何修复我的代码?

最佳答案

map回调中,你应该返回reduce的结果:

function largestOfFour(arr) {
return arr.map(function(innerArray){
return innerArray.reduce(function(previousValue,currentValue){
return currentValue > previousValue ? currentValue : previousValue;
});
});
}

注意有shorter ways of doing that .

关于javascript - 在数组数组的 map() 中使用 reduce(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34140973/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com