forEach的定义和用法
forEach() 方法用于调用数组的每个元素,并将元素传递给回调函数。注意: forEach() 对于空数组是不会执行回调函数的。
array.forEach(function(currentValue, index, arr), thisValue)
- forEach有两个参数,第一个参数是回调函数,第二个参数是回调函数的this指向
- 回调函数有三个参数,分别是当前值,当前值的下标,当前值所属数组对象
const arr = [1, 2, 3]
const obj = {
name: 'obj'
}
//回调函数式箭头函数时,第二个参数不生效,this始终指向window
arr.forEach((ele) => {
console.log(ele, index, arr, this)
}, obj)
//回调函数的this指向obj
arr.forEach(function (ele) {
console.log(ele, index, arr, this)
}, obj)
运行结果如下
自定义的forEach
通过以上的运行结果,我们来实现自定义的myForEach
array.forEach(function(currentValue, index, arr), thisValue)
- myForEach是一个函数,有两个参数,一个是回调函数,一个是回调函数的this指向(默认指向window)
- 实现了遍历
- 遍历的过程中执行了回调函数
Array.prototype.myForEach = function(callback, context=window){
let self = this; //这里的this即指向调用它的arr
let len = self.length;
for(let i = 0; i <len; i++){
//因为context是回调函数this指向,所以使用call改变回调的this指向
//执行callback函数,并将currentValue, index, arr对应的作为参数传递
typeof callback=='function' && callback.call(context, self[i], i, this)
}
}
测试一下
arr.myForEach(function (ele, index, arr) {
console.log(ele, index, arr, this, '-------myForEach')
}, obj)
arr.myForEach((ele, index, arr) => {
console.log(ele, index, arr, this, '-------myForEach')
}, obj)
运行结果