求數組最大值或最小值
阿新 • • 發佈:2018-08-14
原本 ole code log class this指向 最大值 max math
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,就可以了
求數組最大值或最小值