重构map
var arr = [1,3,4,5,5];
Array.prototype.myMap = function(callback,item){
var arr = [];
for(var i=0;i<this.length;i++){
var temp = callback(this[i],i,this);
arr.push(temp);
}
return arr;
}
arr = arr.myMap(function(item,index){
return item*2
})
console.log(arr);//[2, 6, 8, 10, 10]
</script>
重构filter
Array.prototype.myFilter = function(callback){
var arr = [];
for(var i=0;i<this.length;i++){
if(callback(this[i],i,this)){
arr.push(this[i]);
}
}
return arr
}
arr = arr.myFilter(function(item){
return item > 3
})
console.log(arr);//[4, 5, 5]
重构Some
Array.prototype.mySome = function(callback){
var arr = [];
for(var i=0;i<this.length;i++){
if(callback(this[i])){
return true;
}
}
return false
}
arr = arr.mySome(function(item){
return item > 7
})
重构reduce方法
arr = [1, 2, 3]
Array.prototype.myReduce = function (callback,) {
var start = init === undefined ?1:0;
init = init ?? this[0];
for (var i = start; i < this.length; i++) {
var init = callback(init, this[i])
}
return init;
}
var sulter = arr.myReduce(function (v,) {
return v + t;
},2)
console.log(sulter);
重构flat函数
Array.prototype.myFlat = function(depth = 1){
if(depth == 0) return this;
console.log('this=',this);
return this.reduce((v,t)=>{
if(Array.isArray(t)){
return [...v,...t.myFlat(depth-1)]
}else{
return [...v,t]
}
},[])
}
arr= [1,2,3,3,[36,9,9,[0]]]
arr = arr.myFlat()
console.log(arr);//[1, 2, 3, 3, 36, 9, 9, Array(1)]