海納百川,有容乃大
定義:
reduce()方法接受一個函數作為累加器,數組中的每個值(從左向右)開始縮減,最終計算為一個值。對空數組是不會執行回調函數的。
案例:
- 計算數組總和:
var num = [1,2,3,4,5]; var res = num.reduce(function(total,num){ return total+num; //return total + Math.round(num);//對數組元素四舍五入並計算總和 },0); console.log(res);//15 //num.reduce((total,num) => total += num, 0); //沒有初始值initialValue(即上面例子中的0),當數組為0時會拋出異常提示reduce函數沒有初始值,所以為兼容性一般加上initialValue
- 合並二維數組
var red = [[0, 1], [2, 3], [4, 5]].reduce(function(a, b) { return a.concat(b); }, []); console.log(red) VM291:4 (6) [0, 1, 2, 3, 4, 5]
- 統計一個數組中有多少個不重復的單詞
不用reduce時: var arr = ["apple","orange","apple","orange","pear","orange"]; function getWordCnt(){ var obj = {}; for(var i= 0, l = arr.length; i< l; i++){ var item = arr[i]; obj[item] = (obj[item] +1 ) || 1; } return obj; } console.log(getWordCnt()); VM3704:14 {apple: 2, orange: 3, pear: 1} 用reduce時: var arr = ["apple","orange","apple","orange","pear","orange"]; function getWordCnt(){ return arr.reduce(function(prev,next){ prev[next] = (prev[next] + 1) || 1; return prev; },{}); } console.log(getWordCnt()); VM3704:14 {apple: 2, orange: 3, pear: 1}
理解:
reduce(callback,initialValue)會傳入兩個參數,回調函數(callback)和初始值(initialValue)。當沒有傳入初始值時,prev是從數組中第一個元素開始的,next是數組的第二個元素;當傳入初始值(initialValue)后,第一個prev將是initialValue,next將是數組中的第一個元素。
例如:
var arr = ["apple","orange"]; function noPassValue(){ return arr.reduce(function(prev,next){ console.log("prev:",prev); console.log("next:",next); return prev; }); } function passValue(){ return arr.reduce(function(prev,next){ console.log("prev:",prev); console.log("next:",next); prev[next] = 1; return prev; },{}); } console.log("No Additional parameter:",noPassValue()); console.log("----------------"); console.log("With {} as an additional parameter:",passValue());
運行結果為: