[JS] js gets the maximum and minimum values of an array

A summary of the most commonly used methods to obtain the maximum and minimum values ​​of an array in JS

There is an existing array let numList = [12, 5, 7, 23, 6, 45, 55, 4]

1. Loop traversal method

Get the maximum value

// 获取最大值
let max = numList[0]
for(var i = 1; i < numList.length; i++) {
    
    
  if (numList[i] > max) max = numList[i]
}
console.log(max);   // 55

// 获取最小值
let min = numList[0]
for(var i = 1; i < numList.length; i++) {
    
    
  if (numList[i] < min) min = numList[i]
}
console.log(min);   // 4

2. Sorting method


numList.sort(function (a, b) {
    
    
  return a-b; 
})

// 获取最大值
let max = numList[numList.length - 1]
console.log(max);   // 55

// 获取最小值
let min = numList[0]
console.log(min);   // 4

3. Math.min() and Math.max() methods

// 获取最大值
let max = Math.max.apply(null, numList)
console.log(max);   // 55

// 获取最小值
let min = Math.min.apply(null, numList)
console.log(min);   // 4

4. Use the ES6 spread operator

// 获取最大值
let max = Math.max(...numList)
console.log(max);   // 55

// 获取最小值
let min = Math.min(...numList)
console.log(min);   // 4

Guess you like

Origin blog.csdn.net/weixin_44490021/article/details/132606606