使用JavaScript在数组中找到最大数字的三种方法

本文详细介绍了如何在JavaScript中解决Free Code Camp的数组找最大数挑战。通过使用for循环、reduce方法和Math.max结合apply方法,分别展示了三种不同的实现策略。每种方法都有详细的代码注释帮助理解其工作原理。
摘要由CSDN通过智能技术生成

在本文中,我将解释如何解决Free Code Camp的“在数组中返回最大数”挑战。这涉及从每个子数组返回具有最大数目的数组。

我将介绍三种方法:

  1. 带FOR循环
  2. 使用reduce()方法
  3. 使用Math.max()

算法挑战

  • 从每个提供的子数组中返回一个包含最大数目的数组。为简单起见,提供的数组将仅包含4个子数组。
  • 你可以使用简单的for循环遍历数组,并使用数组语法arr
    [i]访问每个成员。
function largestOfFour(arr) {
   
  return arr;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

提供测试用例

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]) should return an array.

largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]) should return [27,5,39,1001].

largestOfFour([[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]]) should return [9, 35, 97, 1000000].

方法1:使用For循环返回数组中的最大数字

这是我的解决方案,带有嵌入的注释可以帮助您理解它

function largestOfFour(arr) {
   
   // Step 1. Create an array that will host the result of the 4 sub-arrays
   var largestNumber = [0,0,0,0];
 
   // Step 2. Create the first FOR loop that will iterate through the arrays
   for(var arrayIndex = 0; arrayIndex < arr.length; arrayIndex++) {
   
   /* The starting point, index 0, corresponds to the first array */
 
    // Step 3. Create the second FOR loop that will iterate through the sub-arrays
    for(var subArrayIndex = 0; subArrayIndex < arr[arrayIndex].length; subArrayIndex++) {
   
    /* The starting point, index 0, corresponds to the first sub-array */
       
       if(arr[arrayIndex][subArrayIndex] > largestNumber[arrayIndex]) {
   
          
          largestNumber[arrayIndex] = arr[arrayIndex][subArrayIndex];
          
       /* FOR loop cycles
          arrayIndex => i
          subArrayIndex => j
          
       Iteration in the first array
          For each iteration: arr[i][j]           largestNumber[i]          if arr[i][j] > largestNumber[i]?     then largestNumber[i] = arr[i][j]
          First iteration:    arr[0][0] => 4      largestNumber[0] => 0     4 > 0? => TRUE                       then largestNumber[0] = 4
          Second iteration:   arr[0][1] => 5      largestNumber[0] => 4     5 > 4? => TRUE                       then largestNumber[0] = 5
          Third iteration:    arr[0][2] => 1      largestNumber[0] => 5     1 > 5? => FALSE                      then largestNumber
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

知柯信安

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值