實際上,map/filter/reduce 也是基于 for 循環(huán)封裝來的射众,通過高階映射實現(xiàn)碟摆。
map
// 使用 for 循環(huán)
const arr1 = [1, 2, 3];
let arr2 = [];
for (let i = 0; i < arr1.length; i++) {
arr2.push(arr1[i] * 2);
}
console.log(arr2); // [2, 4, 6]
// 使用 map 方法
const arr1 = [1, 2, 3];
const arr2 = arr1.map(item => item * 2);
console.log(arr2); // [2, 4, 6]
// 實現(xiàn)自己的 map 方法
Array.prototype.myMap = function(fn) {
const newArr = [];
for (let i = 0; i < this.length; i++) {
newArr.push(fn(this[i]));
}
return newArr;
};
const arr1 = [1, 2, 3];
const arr2 = arr1.myMap(item => item * 2);
console.log(arr2); // [2, 4, 6]
filter
// 使用 for 循環(huán)
const arr1 = [1, 2, 3];
const arr2 = [];
for (let i = 0; i < arr1.length; i++) {
arr1[i] > 2 && arr2.push(arr1[i]);
}
console.log(arr2); // [3]
// 使用 filter 方法
const arr1 = [1, 2, 3];
const arr2 = arr1.filter(item => item > 2);
console.log(arr2); // [3]
// 實現(xiàn)自己的 filter 方法
Array.prototype.myFilter = function(fn) {
const newArr = [];
for (let i = 0; i < this.length; i++) {
fn(this[i]) && newArr.push(this[i]);
}
return newArr;
};
const arr1 = [1, 2, 3];
const arr2 = arr1.myFilter(item => item > 2);
console.log(arr2); // [3]
reduce
// 使用 for 循環(huán)
const arr1 = [1, 2, 3];
let sum = 0;
for (let i = 0; i < arr1.length; i++) {
sum = sum + arr1[i];
}
console.log(sum);
// 使用 reudce 方法
const arr1 = [1, 2, 3];
const sum = arr1.reduce((perv, current) => {
return perv + current;
});
console.log(sum);
// 實現(xiàn)自己的 reduce 方法
Array.prototype.myReduce = function(fn, initValue) {
for (let i = 0; i < this.length; i++) {
initValue = fn(initValue, this[i], i, this);
}
return initValue;
};
const arr1 = [1, 2, 3];
const sum = arr1.myReduce((perv, current) => {
return perv + current;
}, 0);
console.log(sum);