If there is a requirement:
Find the maximum and minimum values in the array let arr = [72, 6, 13, 7, 400, 55, 88, 100, 800]
analyze:
①: Declare a variable max that holds the largest element.
②: The default maximum value can be the first element in the array.
③: Traverse the array and compare each array element with max.
④: If the array element is greater than max, store the array element in max, otherwise continue to the next round of comparison.
⑤: Finally output this max.
The minimum value is the same
code:
let arr = [72, 6, 13, 7, 400, 55, 88, 100, 800]
// max里面要存的是最大值,初始值为数组的第一个元素
let max = arr[0]
// min 要存放的是最小值,初始值为数组的第一个元素
let min = arr[0]
// 遍历数组
for (let i = 1; i < arr.length; i++) {
// 如果max 比 数组元素里面的值小,我们就需要把这元素赋值给 max
// if (max < arr[i]) max = arr[i]
max < arr[i] ? max = arr[i] : max
// 如果min 比 数组元素大, 我们就需要把数组元素给min
min > arr[i] ? min = arr[i] : min
}
// 输出 max,min
console.log(`最大值是: ${max}`) // 最大值是: 800
console.log(`最小值是: ${min}`) // 最小值是: 6