reduce/reduceRight

使用 reduce 和 reduceRight 方法可以汇总数组元素的值,具体用法如下:

reduce

function appendCurrent (previousValue, currentValue) {
    return previousValue + "::" + currentValue;
}
var elements = ["abc", "def", 123, 456];
var result = elements.reduce(appendCurrent);
document.write(result); //abc::def::123::456

reduceRight

function appendCurrent (previousValue, currentValue) {
    return previousValue + "::" + currentValue;
}
var elements = ["abc", "def", 123, 456];
var result = elements.reduceRight(appendCurrent);
document.write(result); //456::123::def::abc

 

上一篇:js 高阶函数(map/reduce/filter/sort)


下一篇:ZooKeeper学习笔记(二)——内部原理