Open
Description
一、forEach
代码实现
Array.prototype.myForeach = function(callback, thisArg = null){
if(typeof callback != "function"){
throw new TypeError(callback + " is not a function");
}
for(let i = 0; i < this.length; i++){
callback.call(thisArg, this[i], i, this);
}
}
测试
["a", "b", "c"].myForeach(function(item, index, arr){
console.log(item, index, arr);
})
二、map
代码实现
Array.prototype.myMap = function(callback, thisArg = null){
if(typeof callback != "function"){
throw new TypeError(callback + " is not a function");
}
let res = new Array(this.length);
for(let i = 0; i < this.length; i++){
let data = callback.call(thisArg, this[i], i, this);
res.push(data);
}
return res;
}
测试
let res = [1, 2, 3].myMap(function(item, index, arr){
return item + 2;
})
// [3, 4, 5]
三、reduce
代码实现
Array.prototype.myReduce= function(fn, init){
for(let i = 0; i < this.length; i++){
if(init){
init = fn.call(null, init, this[i], i, this);
}else{
init = fn.call(null, this[i], this[i + 1], i + 1, this);
i++;
}
}
return init;
}
测试
let sum = [1, 2, 3].myReduce(function(prev, next, currentIndex, array){
return prev + next;
});
// 6
四、filter
代码实现
Array.prototype.myFilter = function(callback, thisArg = null){
if(typeof callback != "function"){
throw new TypeError(callback + " is not a function");
}
let arr = []
for(let i = 0; i < this.length; i++){
callback.call(thisArg, this[i]) && arr.push(this[i]);
}
return arr;
}
测试
let res = [1, 2, 3].myFilter(function(item){
return item > 2;
});
console.log(res); // [3]