ES-6對數組做了一些擴展,有些人對於reduce有些疑惑,其實這個東西非常簡單。
自己實現一個reduce你就明白了
Array.prototype.redu = function(func) { let result = this[0]; for (let i = 1; i < this.length; i++) { result = func(result, this[i], i) } return result } const arr = [1, 5, 8, 10, 2, 3, 4, 60, 5] let str = arr.redu((temp, item, index) => { if (index !== arr.length - 1) { return temp += item } else { return (temp + item) / arr.length } }) console.log(str)
再reduce內部是從1開始遍歷,將數組第一項作為臨時變量。
每次循環拿到函數計算結果重置result,再將其傳入函數,一個循環下來reduce就會拿到最終結果,也就是第一個參數的結果。
所以說當你不理解一個抽象的現象時就嘗試自己實現一下。