js数组 foreach 源码解析

// 原来的方法
(method) Array<T>.forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void
  • 看到forEach里的第一个参数是 callbackfn : 回调方法,可以把数组里面的 value,index,list 全部返回给 callbackfn 方法里面。
const list = ['a', 'b', 'c', 'd'];
// 注意不能使用 => (fn) {...} 写法,因为this会找不到对象的
// item: 返回每个数组的值
// index: 返回数组对应索引 0 1 2....
// array: 返回循环的数组本身自己
Array.prototype.newForEach = function (fn: (item: any, index: number,array: any[]) => void) {
  console.log(this); // 这里的this会指向 list - ['a', 'b', 'c', 'd']
  const len = this.length;
  for (let i = 0; i < len; i++) {
    // 将元素传给回调函数
    fn(this[i], i,this);
  }
};
list.newForEach((item, index) => {
  console.log(item, index);
});
// a 0 b 1 c 2 d 3
  • 看到forEach里的第二个参数是 thisArg :意思是指向回调函数的this指向
var array1 = ['a', 'b', 'c'];
var array2 = ['1','2','3'];
array1.forEach(function(currentValue, index, arr) {
    console.log(currentValue, index, arr, this);
},array2);

# 输出
// 如果给 forEach() 传递了 thisArg 参数,当调用时,它将被传给 callback 函数,作为它的 this 值。否则,将会传入 undefined 作为它的 this 值
> "a" 0 ["a", "b", "c"] ["1", "2", "3"] 
> "b" 1 ["a", "b", "c"] ["1", "2", "3"]
> "c" 2 ["a", "b", "c"] ["1", "2", "3"]

  • 最终代码

const list = ['a', 'b', 'c', 'd'];
const list2 = [1, 2, 3];
// 注意不能使用 => (fn) {...} 写法,因为this会找不到对象的
// item: 返回每个数组的值
// index: 返回数组对应索引 0 1 2....
// array: 返回循环的数组本身自己
Array.prototype.newForEach = function (
  fn: (item: any, index: number, array: any[]) => void,
  thisArg?: any,
) {
  console.log(this); // 这里的this会指向 list - ['a', 'b', 'c', 'd']
  const len = this.length;
  for (let i = 0; i < len; i++) {
    // 将元素传给回调函数
    if (thisArg) {
      fn.call(thisArg, this[i], i, this);
    } else {
      fn(this[i], i, this);
    }
  }
};
list.newForEach(function (currentValue, index, arr) {
  console.log(currentValue, index, arr, this);
}, list2);

在这里插入图片描述

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值