无所不能的Array reduce

  目录

Array的reduce方法分析

Array有很多实例方法,reduce,map,filter,find,some,every…
这里,基础是reduce,可以利用它去实现其它所有方法。
我们先来看看reduce如何使用:

reduce

reduce的使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// api
Array.prototype.reduce = function(callback, initialValue) {

}
// Accumulator (acc) (累计器) 如果传入了initialValue,Accumulator的初始值就是initialValue,没传入就是数组的第一个值
// Current Value (cur) (当前值)
// Current Index (idx) (当前索引)如果传入了initialValue,索引从0开始,没传入从1开始
// Source Array (src) (源数组)
const callback = function(acc, cur, idx, src) {
return someVal;
}
// demo
let arr = [1,2,3,4,5,6,7,8,9,10];
let sum = arr.reduce(function(acc, cur, idx, src) {
return acc + cur;
}, 0);
console.log(sum); // 55

reduce方法的实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Array.prototype.myReduce = function (callback, initVal) {
for (let i = 0; i < this.length; i++) {
initVal = callback(initVal, this[i], i, this)
}
return initVal
}
// initVal不传的时候,改进版
Array.prototype.myReduce = function(callback, initVal) {
let arr = this;
let i = initVal?0:1;
initVal = initVal || arr[0];
for(;i<arr.length; i++) {
initVal = callback(initVal, arr[i], i, arr);
}
return initVal;
}

利用reduce实现其它方法

map

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Array.prototype.myMap = function(callback) {
let tempArr = [];
this.reduce(function(pre, cur, index) {
tempArr.push(callback(cur, index));
}, this[0]);
return tempArr;
}
let arr = [1,2,3,4,5];
let newArr = arr.myMap((item, index)=> {
return {
val: item,
num: index + 1
}
});
console.log(newArr);

filter

1
2
3
4
5
6
7
8
9
10
11
12
Array.prototype.myFilter = function(callback) {
let tempArr = [];
this.reduce(function(pre, cur, index) {
if(callback(cur, index)) tempArr.push(cur);
}, this[0]);
return tempArr;
}
let arr = [1,2,3,4,5,6,7,8,9,10,11,12];
let newArr = arr.filter((item, index)=> {
return item%2===0&&item%3===0;
});
console.log(newArr);

find

1
2
3
4
5
6
7
8
9
10
11
12
Array.prototype.myFind = function(callback) {
let target = null;
this.reduce(function(pre, cur, index) {
if(callback(cur, index)&&!target) target = cur;
}, this[0]);
return target;
}
let arr = [1,2,3,4,5,6,7,8,9,10,11,12];
let newArr = arr.myFind((item, index)=> {
return item > 3;
});
console.log(newArr);

some

1
2
3
4
5
6
7
8
9
10
11
12
Array.prototype.mySome = function(callback) {
let bResult = false;
this.reduce(function(pre, cur, index) {
callback(cur, index)&&(bResult=true);
}, this[0]);
return bResult;
}
let arr = [1,2,3,4,5,6,7,8,9,10,11,12];
let result = arr.mySome((item, index)=> {
return item > 11;
});
console.log(result);

every

1
2
3
4
5
6
7
8
9
10
11
12
Array.prototype.myEvery = function(callback) {
let bResult = false;
this.reduce(function(pre, cur, index) {
!callback(cur, index)&&(bResult=true);
}, this[0]);
return !bResult;
}
let arr = [1,2,3,4,5,6,7,8,9,10,11,12];
let result = arr.myEvery((item, index)=> {
return item > 1;
});
console.log(result);

总结

其实不用reduce也可以实现,但是利用reduce来实现,侧面反映了reduce功能的强大,在实际项目中灵活运用reduce,会事半功倍哦。