JS如何实现手写forEach算法

发布时间:2020-07-29 13:46:43 作者:小猪
来源:亿速云 阅读:349

小编这次要给大家分享的是JS如何实现手写forEach算法,文章内容丰富,感兴趣的小伙伴可以来了解一下,希望大家阅读完这篇文章之后能够有所收获。

手写 forEach

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

arr.forEach(callback(currentValue [, index [, array]])[, thisArg]);

如果提供了一个 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);
 }
};

看完这篇关于JS如何实现手写forEach算法的文章,如果觉得文章内容写得不错的话,可以把它分享出去给更多人看到。

推荐阅读:
  1. python如何实现kNN算法识别手写体数字
  2. python使用KNN算法识别手写数字

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

js foreach fo

上一篇:JDK14中的java tools是什么

下一篇:解决pycharm中文乱码的问题

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》