JavaScript find the maximum value of the elements in the array

Claim:

Find [2,6,1,77,52,25,7]the maximum value in the array .

Realization ideas:

  1. Declare a variable that holds the largest elementmax
  2. The default maximum value is maxdefined as the first element in the arrayarr[0]
  3. Traverse this array and compare each array element maxwith
  4. If the array element is greater than max, save the array element in maxit, otherwise continue to the next round of comparison
  5. Finally output thismax

Code:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // 利用函数求数组 [3, 77, 44, 99, 143] 中的最大数值。
        function getArrMax(arr) {
     
      // arr 接受一个数组  arr =  [3, 77, 44, 99, 143]
            var max = arr[0];
            for (var i = 1; i < arr.length; i++) {
     
     
                if (max < arr[i]) {
     
     
                    max = arr[i];
                }
            }
            return max;
        }
        // getArrMax([3, 77, 44, 99, 143]); // 实参是一个数组送过去
        var re = getArrMax([3, 77, 44, 99, 143]);
        console.log(re);
    </script>
</body>

</html>

Output result:

Insert picture description here

Guess you like

Origin blog.csdn.net/Jack_lzx/article/details/109241583