当前位置: 移动技术网 > IT编程>开发语言>JavaScript > JS实现手写 forEach算法示例

JS实现手写 forEach算法示例

2020年05月10日  | 移动技术网IT编程  | 我要评论

本文实例讲述了js实现手写 foreach算法。分享给大家供大家参考,具体如下:

手写 foreach

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

arr.foreach(callback(currentvalue [, index [, array]])[, thisarg]);

  • callback

    • currentvalue
      数组中正在处理的当前元素。
    • index 可选
      数组中正在处理的当前元素的索引。
    • array 可选
      foreach() 方法正在操作的数组。
    • thisarg 可选
      可选参数。当执行回调函数 callback 时,用作 this 的值。
  • 没有返回值

如果提供了一个 thisarg 参数给 foreach 函数,则参数将会作为回调函数中的 this 值。否则 this 值为 undefined。回调函数中 this 的绑定是根据函数被调用时通用的 this 绑定规则来决定的。

let arr = [1, 2, 3, 4];

arr.foreach((...item) => console.log(item));

// [1, 0, array(4)] 当前值

function counter() {
 this.sum = 0;
 this.count = 0;
}

// 因为 thisarg 参数(this)传给了 foreach(),每次调用时,它都被传给 callback 函数,作为它的 this 值。
counter.prototype.add = function(array) {
 array.foreach(function(entry) {
  this.sum += entry;
  ++this.count;
 }, this);
 // ^---- note
};

const obj = new counter();
obj.add([2, 5, 9]);
obj.count;
// 3 === (1 + 1 + 1)
obj.sum;
// 16 === (2 + 5 + 9)

  • 每个数组都有这个方法
  • 回调参数为:每一项、索引、原数组
array.prototype.foreach = function(fn, thisarg) {
 var _this;
 if (typeof fn !== "function") {
  throw "参数必须为函数";
 }
 if (arguments.length > 1) {
  _this = thisarg;
 }
 if (!array.isarray(arr)) {
  throw "只能对数组使用foreach方法";
 }

 for (let index = 0; index < arr.length; index++) {
  fn.call(_this, arr[index], index, arr);
 }
};

感兴趣的朋友可以使用在线html/css/javascript代码运行工具:测试上述代码运行效果。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网