gpt4 book ai didi

javascript - 返回最大的数组

转载 作者:行者123 更新时间:2023-11-30 09:30:35 24 4
gpt4 key购买 nike

我一直在尝试解决这个练习题:

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/

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