forEach() 方法对数组的每个元素执行一次提供的函数。

forEach() 方法对数组的每个元素执行一次提供的函数。(ES5)

 // 求和
    function sum(...arg) {
        let sumNumber = 0;
        arg.forEach((eve) => {
            sumNumber += eve;
        });
        return sumNumber
    }

    console.log(sum(1, 2, 3));

forEach描述:
    第一个参数是callback回调函数;

          里面有三个参数:

                 第一个参数是ele:数组的值

                 第二个参数是index:下标值

                 第三个参数是arr:正在执行的当前数组

    第二个参数是thisArg,默认为this指向window

<script>
  /*
      forEach():
        第一个参数是callback回调函数;
          里面有三个参数:
            第一个参数是ele:数组的值
            第二个参数是index:下标值
            第三个参数是arr:正在执行的当前数组
        第二个参数是thisArg,默认为this指向window
  */
  const arr = [
    { name: '张三', age: 21 },
    { name: '李四', age: 22 },
    { name: '王五', age: 23 },
  ];
  let obj = {
    naem: 'xyz'
  }
  function deal(ele, index, curArr) {
    console.log(ele, index, curArr, this)
  }

  arr.forEach(deal)
  arr.forEach(deal, obj)
</script>

result:

 通过源码实现forEach方法:

//通过源码实现forEach方法
  const arr = [
    { name: '张三', age: 21 },
    { name: '李四', age: 22 },
    { name: '王五', age: 23 },
  ];
  Array.prototype.myForEach = function (func) {
    let _this = arguments[1] != undefined ? arguments[1] : window;
    for (let i = 0; i < this.length; i++) {
      func.apply(_this, [this[i], i, this])
    }
  }
  let obj = {
    naem: 'xyz'
  }

  function deal(ele, index, curArr) {
    console.log(ele, index, curArr, this)
  }

  arr.myForEach(deal)
  arr.myForEach(deal, obj)

 result:

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值