一、自定义forEach
Array.prototype.myForEach = function(callback) {
for(let i=0;i<this.length;i++){
callback(this[i],i,this)
}
}
const arr1=[1,2,3]
arr1.myForEach((item, index,data)=>{
console.log(item)
console.log(index)
console.log(data);
})
二、自定义map方法
Array.prototype.myMap = function(callback) {
const arr=[]
for(let i=0;i<this.length;i++){
const res=callback(this[i],i,this)
arr.push(res)
}
return arr
}
const arr1=[1,2,3]
const arr2=arr1.myMap((item, index,data)=>{
console.log(item)
console.log(index)
console.log(data);
return item+'hhhhhhh'
})
console.log(arr2);
三、自定义filter方法
Array.prototype.myFilter = function(callback) {
const arr=[]
for(let i=0;i<this.length;i++){
const res=callback(this[i],i,this)
if(res){
arr.push(this[i])
}
}
return arr
}
const arr1=[1,2,3]
const arr2=arr1.myFilter((item, index,data)=>item!==3)
console.log(arr2);
四、自定义reduce方法
Array.prototype.myReduce = function(callback,total) {
for(let i=0;i<this.length;i++){
const res=callback(total,this[i],i)
total=res
}
return total
}
const arr1=[1,6,3]
const arr2=arr1.myReduce((prev, cur,index)=>{
return prev+cur
},0)
console.log(arr2);
五、自定义every方法
Array.prototype.myEvery = function(callback) {
for(let i=0;i<this.length;i++){
const res=callback(this[i],i,this)
if(!res){
return false
}
}
return true
}
const arr1=[1,6,3]
const arr2=arr1.myEvery((curr,index,arr)=>{
return index>0
})
console.log(arr2);
六、自定义some方法
Array.prototype.myEvery = function(callback) {
for(let i=0;i<this.length;i++){
const res=callback(this[i],i,this)
if(res) return true
}
return false
}
const arr1=[1,6,3]
const arr2=arr1.myEvery((curr,index,arr)=>{
return index>1
})
console.log(arr2);
本文详细介绍了如何在JavaScript中自定义实现数组的forEach、map、filter、reduce、every和some方法,深入理解这些基本操作对于提升前端开发能力至关重要。
108

被折叠的 条评论
为什么被折叠?



