本文摘自PHP中文网,作者醉折花枝作酒筹,侵删。
在javascript中,reduce是归并方法,语法格式为“数组.reduce(function(前一个值,当前值,索引,数组对象){},初始值)”。reduce方法接收一个函数作为累加器,数组中的每个值开始缩减,最终计算为一个值。

本教程操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。
与之前两篇文章( map()的实现 ,filter()的实现 )中的迭代方法不一样,reduce() 是归并方法。
reduce 接收两个参数:
第一个参数是在每一项上调用的函数
该函数接收 4 个参数:
前一个值 prev
当前值 cur
项的索引 index
数组对象 array
第二个可选参数是作为归并基础的初始值
reduce 方法返回一个最终的值。
代码表示:
1 | arr.reduce( function (prev, cur, index, arr){}, initialValue)
|
归并
与之前的迭代不同,归并不是对每一项都执行目标函数,而是可以概括为如下两步:
不断地对数组的前两项“取出”,对其执行目标函数,计算得到的返回值
把上述返回值“填回”数组首部,作为新的 array[0]
持续循环执行这个过程,直到数组中每一项都访问了一次
返回最终结果
举例说明
对数组 [1,2,3] 归并执行 (prev, cur) => prev + cur,流程如图:
所以得到 6 。
实现
第一版
根据这个思路,得到第一版代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | Array.prototype.fakeReduce = function fakeReduce(fn, base) {
let initialArr = this ;
let arr = initialArr.concat();
if (base) arr.unshift(base);
let index;
while (arr.length > 2) {
index = initialArr.length - arr.length + 1;
let newValue = fn.call( null , arr[0], arr[1], index, initialArr);
arr.splice(0, 2);
arr.unshift(newValue);
}
index += 1;
let result = fn.call( null , arr[0], arr[1], index, initialArr);
return result;
};
|
注意点:
队列方法 unshift()
可以从数组首部加入任意个项,返回值是新数组的长度,影响原数组
splice() 方法,高程三将其誉为最强大的数组方法
删除任意数量的项
指定 2 个参数: (删除起始位置, 删除项个数)
插入任意数量的项
指定 3 个参数: (起始位置,0,要插入的项)
第二个参数 0 即为要删除的个数
替换,即删除任意数量的项的同时,插入任意数量的项
指定 3 个参数:(起始位置,要删除的个数, 要插入的任意数量的项)
返回值始终是一个数组,包含从原始数组中删除的项。若未删除任何项,返回空数组,影响原数组
改进版
从上面的总结可以看出,splice() 方法完全可以取代 unshift() 方法。
而且,第一版中存在一些重复代码,也可以改进。
由此得到第二版代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | Array.prototype.fakeReduce = function fakeReduce(fn, base) {
let initialArr = this ;
let arr = initialArr.concat();
if (base) arr.unshift(base);
let index, newValue;
while (arr.length > 1) {
index = initialArr.length - arr.length + 1;
newValue = fn.call( null , arr[0], arr[1], index, initialArr);
arr.splice(0, 2, newValue);
}
return newValue;
};
|
检测:
1 2 3 4 5 6 7 | let arr = [1, 2, 3, 4, 5];
let sum = arr.fakeReduce((prev, cur, index, arr) => {
console.log(prev, cur, index, arr);
return prev * cur;
}, 100);
console.log(sum);
|
输出:
1 2 3 4 5 6 | 100 1 0 [ 1, 2, 3, 4, 5 ]
100 2 1 [ 1, 2, 3, 4, 5 ]
200 3 2 [ 1, 2, 3, 4, 5 ]
600 4 3 [ 1, 2, 3, 4, 5 ]
2400 5 4 [ 1, 2, 3, 4, 5 ]
12000
|
最后加上类型检测等
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | Array.prototype.fakeReduce = function fakeReduce(fn, base) {
if ( typeof fn !== "function" ) {
throw new TypeError( "arguments[0] is not a function" );
}
let initialArr = this ;
let arr = initialArr.concat();
if (base) arr.unshift(base);
let index, newValue;
while (arr.length > 1) {
index = initialArr.length - arr.length + 1;
newValue = fn.call( null , arr[0], arr[1], index, initialArr);
arr.splice(0, 2, newValue);
}
return newValue;
};
|
【推荐学习:javascript高级教程】
以上就是javascript如何使用reduce方法的详细内容,更多文章请关注木庄网络博客!
相关阅读 >>
javascript如何使用reduce方法
更多相关阅读请进入《reduce》频道 >>
人民邮电出版社
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者
转载请注明出处:木庄网络博客 » javascript如何使用reduce方法