Claim:
Find [2,6,1,77,52,25,7]
the maximum value in the array .
Realization ideas:
- Declare a variable that holds the largest element
max
- The default maximum value is
max
defined as the first element in the arrayarr[0]
- Traverse this array and compare each array element
max
with - If the array element is greater than
max
, save the array element inmax
it, otherwise continue to the next round of comparison - Finally output this
max
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>