以前看到reduce方法,總是看得我頭皮發麻,今天無意間又遇到他了,於是學習了下,接觸之后,覺得這個方法還挺好用的,在很多地方都可以派上用場,比如,數組中元素求和、數組去重、求數組中的最大值或最小值等等都可以用到它。
reduce() 方法接收一個函數作為累加器,數組中的每個值(從左到右)開始縮減,最終計算為一個值。
語法:array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
可以看出它接收一個回調函數和一個初始值。
其中total為初始值或者計算后的返回值(必須)、currentValue為當前元素(必須)、currentIndex為當前元素索引(可選)、arr為當前元素所屬的對象(可選)、initialValue為傳遞給函數的初始值
案例1:數組去重
// 數組去重 var arr = [12, 34, 34, 342, 345, 34, 123, 345, 45, 12] var newArr = arr.reduce(function (prev, next) { prev.indexOf(next) == -1 && prev.push(next) return prev }, []) console.log(arr) // [12, 34, 34, 342, 345, 34, 123, 345, 45, 12] console.log(newArr) // [12, 34, 342, 345, 123, 45]
初始化一個空數組,判斷下一個元素是否在當前數組中,不存在則添加到當前數組中。
案例2:數組中元素求和
// 數組求和 var arr = [1, 2, 3, 4, 5] var total = arr.reduce(function (prev, next) { return prev + next }, 0) console.log(total)
將0當做reduce回調函數中的初始值,然后依次累加
案例3:求數組中最大值或最小值:
// 獲取數組中最大值 var arr = [134798, 3478973, 12, 345, 355, 425, 1342356, 3425566, 7908798] var max = arr.reduce(function (prev, next) { return Math.max(prev, next) // Math.min(prev, next) }, 0) console.log(max)
tips:initialValue為傳遞給函數的初始值,假如該值不存在時,則回調函數的初始值為數組中的第一項,即回調函數中的prev值