求数组最大值或最小值

1. 一维数组

const arr = [1, 5, 9, 0, 11]
const maxValue = Math.max.apply(null, arr )
const minValue = Math.min.apply(null, arr )
console.log(maxValue ,minValue)

2. 多维数组

const arr1 = [2, 5, 8]
const arr2 = [9, 5, 2]
const convertArr = arr1.join(',').split(',')   // 转为一维数组
const maxValue = Math.max.apply(null, convertArr)
const minValue = Math.min.apply(null, convertArr)

解释一下为什么可以通过apply这种方式来求最值,这是因为 

Math.max() 或  Math.min()方法不能接收一个数组为参数,我们要想直接求最值,只能这样用:
const arr = Math.max(1, 5, 8, 2)
console.log(arr)

所以我们就要把数组里面的值一一取出来,这时就可以利用apply的特性,即接受数组为 非第一个参数, 再把原本的第一个this指向的参数置为null,就可以了

猜你喜欢

转载自www.cnblogs.com/aloehui/p/9477432.html