天天看點

如何求數組的最大值和最小值

前言

取出數組中的最大值或者最小值是開發中常見的需求,但你能想出幾種方法來實作這個需求呢?

Math.max

JavaScript 提供了 Math.max 函數傳回一組數中的最大值,用法是:

Math.max([value1[,value2, ...]])      

值得注意的是:

  1. 如果有任一參數不能被轉換為數值,則結果為 NaN。
  2. max 是 Math 的靜态方法,是以應該像這樣使用:Math.max(),而不是作為 Math 執行個體的方法 (簡單的來說,就是不使用 new )
  3. 如果沒有參數,則結果為 

    -Infinity

     (注意是負無窮大)

而我們需要分析的是:

1.如果任一參數不能被轉換為數值,這就意味着如果參數可以被轉換成數字,就是可以進行比較的,比如:

Math.max(true, 0) // 1 Math.max(true, '2', null) // 2 Math.max(1, undefined) // NaN Math.max(1, {}) // NaN      

2.如果沒有參數,則結果為 -Infinity,對應的,Math.min 函數,如果沒有參數,則結果為 Infinity,是以:

var min = Math.min();
var max = Math.max(); console.log(min > max);      

了解了 Math.max 方法,我們以求數組最大值的為例,思考有哪些方法可以實作這個需求。

原始方法

最最原始的方法,莫過于循環周遊一遍:

var arr = [6, 4, 1, 8, 2, 11, 23]; var result = arr[0]; for (var i = 1; i < arr.length; i++) { result = Math.max(result, arr[i]); } console.log(result);      

reduce

既然是通過周遊數組求出一個最終值,那麼我們就可以使用 reduce 方法:

var arr = [6, 4, 1, 8, 2, 11, 23]; function max(prev, next) { return Math.max(prev, next); } console.log(arr.reduce(max));      

排序

如果我們先對數組進行一次排序,那麼最大值就是最後一個值:

var arr = [6, 4, 1, 8, 2, 11, 23]; arr.sort(function(a,b){return a - b;}); console.log(arr[arr.length - 1])      

eval

Math.max 支援傳多個參數來進行比較,那麼我們如何将一個數組轉換成參數傳進 Math.max 函數呢?eval 便是一種

var arr = [6, 4, 1, 8, 2, 11, 23]; var max = eval("Math.max(" + arr + ")"); console.log(max)      

apply

使用 apply 是另一種。

var arr = [6, 4, 1, 8, 2, 11, 23]; console.log(Math.max.apply(null, arr))      

ES6 ...

使用 ES6 的擴充運算符:

var arr = [6, 4, 1, 8, 2, 11, 23]; console.log(Math.max(...arr))      

轉載于:https://www.cnblogs.com/guaidianqiao/p/7771469.html