JS实现⼿写forEach算法⽰例
本⽂实例讲述了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;
}
// 因为 thisArg 参数(this)传给了 forEach(),每次调⽤时,它都被传给 callback 函数,作为它的 this 值。
Counter.prototype.add = function(array) {
array.forEach(function(entry) {
this.sum += entry;
++unt;
}, this);
// ^---- Note
};
const obj = new Counter();
obj.add([2, 5, 9]);
// 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⽅法";
}
js实现正则表达式校验for (let index = 0; index < arr.length; index++) {
fn.call(_this, arr[index], index, arr);
}
};
更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《》、《》、《》、《》、《》、《》及《》希望本⽂所述对⼤家JavaScript程序设计有所帮助。