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就会拿到最终结果,也就是第一个参数的结果。
所以说当你不理解一个抽象的现象时就尝试自己实现一下。