javascript reduce方法

reduce怎么玩的?

reduce是处理数组元素的一种方法,说点个人的理解:

reduce方法接受两个参数,第一个参数是一个处理函数,第二个参数是一个初始值。先说第一个:

var arr = ["apple","orange","apple","orange","pear","orange"];
arr.reduce(function(previous, current, index, array){
    console.log(previous, current, index, array);
})
//上面的代码会输出:
// apple orange 1 ["", "orange", "apple", "orange", "pear", "orange"]
// undefined "apple" 2 ["apple", "orange", "apple", "orange", "pear", "orange"]
// undefined orange 3 ["apple", "orange", "apple", "orange", "pear", "orange"]
// undefined pear 4 ["apple", "orange", "apple", "orange", "pear", "orange"]
// undefined orange 5 ["apple", "orange", "apple", "orange", "pear", "orange"]
// undefined

处理函数有四个参数,分别代表:

previous:通过上一次调用回调函数获得的值。
current:当前数组元素的值。
index:当前数组元素的数字索引。
array:包含该元素的数组对象。

由于上面的例子我们没有在调用reduce方法时传入一个初始值,所以在第一次执行回调时,previous 是数组的第一个元素,current则是数组的第二个元素,index为 1,array则是整个数组。

当第二次执行回调的时候,由于previous是指通过上一次调用回调函数获得的值,然而我们并没有在回调函数中返回任何值,所以第二次previous的值为undefined,当我们在毁掉函数的末尾添加一句话return previous;。这时,你会发现所有的undefined都会变成apple

下面简单修改一下代码,添加一个新的方法:

function getWordCnt(){
    return arr.reduce(function(previous, current){
        previous[current] = (previous[current] + 1) || 1;
        return previous;
    },{});
}
console.log(getWordCnt());   //Object {apple: 2, orange: 3, pear: 1}

上边的例子,我们给reduce方法传入了一个空对象作为初始值,那在第一次执行回调的时候,previous就是这个{},current是数组的第一个元素appleindex为 0,array还是整个数组。

如上代码实现了一个统计数组中相同元素出现的次数的功能,在回调函数中我们每次都会判断previous中是否已经存在了当前元素,并作相应的处理,之后将previous返回。最后我们会将处理结果对象返回。

reduce的用法

reduce可以用在求数组的合,统计数组中元素的个数,将二维数组转化成一维数组(concat方法)等等,主要还是看自己的想法。