forEach()
对数组的每个元素执行一次提供的函数。
遍历数组的每一项,特点是如果数组中途被修改,依然按照初始值进行不会随之改变。
原理是封装一个函数,接收函数作为参数,函数里面设置循环,遍历传进来的每个参数和对应的下标。
// 封装一个数组的 myForEach 方法 传参为一个函数
function myForEach(fn){
// 循环数组的每一项 谁调用的this就指向谁
for(let i = 0; i < this.length; i++){
// 循环传进来的函数的三个参数
fn(this[i],i,this)
}
}
// 定义一个数组
let arr = ['4','5','6']
// 将定义的这个数组方法放到Array的prototype下面
Array.prototype.myForEach = myForEach;
console.log(Array.prototype)
// 数组arr调用myForEach方法并传参
arr.myForEach(function(item,index,arr){
// 打印传进来的参数
console.log(item,index,arr)
})
网友评论