我正在进行freecodecamp挑战,我想知道为什么我的代码不起作用以及如何纠正它.
目标是"返回由每个提供的子阵列中最大数字组成的数组".
我的尝试是使用reduce作为map函数映射输入数组:
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]]));
Run Code Online (Sandbox Code Playgroud)
目前的输出是: [undefined, undefined]
我该如何修复我的代码?
在map回调中,您应该返回以下结果reduce:
function largestOfFour(arr) {
return arr.map(function(innerArray){
return innerArray.reduce(function(previousValue,currentValue){
return currentValue > previousValue ? currentValue : previousValue;
});
});
}
Run Code Online (Sandbox Code Playgroud)
请注意,有更短的方法.