我一直在尝试解决这个练习问题:
Return an array consisting of the largest number from each provided sub-array. For simplicity, the provided array will contain exactly 4 sub-arrays.
但是我的代码只返回整个数组中的单个元素,如果我unshift
所有最大元素,它会产生完全错误的结果,我尝试单独执行嵌套循环,它工作得很好,但是与外循环结合时会产生问题。
function largestOfFour(arr)
{
// You can do this!
var max = 0;
var largestArray =[];
for (var i = 0; i <4; i++)
{
for (var j = 0; j <4; j++)
{
if (arr[i][j]>max)
{
max=arr[i][j];
largestArray.unshift(max);
//console.log(max);
}
}
}
console.log(largestArray);
return max;
}
largestOfFour([[4, 5, 1, 13], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
最佳答案
如何修复代码(请参阅代码中的注释):
function largestOf(arr) {
var max;
var largestArray = [];
for (var i = 0; i < arr.length; i++) { // the arr length is the number of sub arrays
max = -Infinity; // max should be reinitialized to the lowest number on each loop
for (var j = 0; j < arr[i].length; j++) { // the length is the number of items in the sub array
if (arr[i][j] > max) { // just update max to a higher number
max = arr[i][j];
}
}
largestArray.push(max); // push max after the internal loop is done, and max is known
}
return largestArray; // return the largest array
}
var result = largestOf([[4, 5, 1, 13], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
console.log(result);
另一个解决方案是使用Array#map ,然后申请Math#max到每个子数组以获得其最大值:
function largestOf(arr) {
return arr.map(function(s) {
return Math.max.apply(Math, s);
});
}
var result = largestOf([[4, 5, 1, 13], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
console.log(result);
关于javascript - 返回最大的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46522359/