美文网首页
用原生js实现forEach()方法

用原生js实现forEach()方法

作者: 不会潜水的猫小喵 | 来源:发表于2019-03-26 13:54 被阅读0次

forEach() 方法从头至尾遍历数组,为每个元素调用指定的函数。它接收两个参数:要在每一项上运行的函数和运行该函数的作用域对象——影响this的值(可选的)。传递的函数作为第一个参数,会接收三个参数:数组项的值、该项在数组中的位置和数组对象本身。
forEach() 方法没有返回值,本质上与使用for循环迭代数组一样。它是es5新增的数组迭代方法,使用方法如下:

var arr = [1, 2, 3, 4, 5];
arr.forEach(function(item, index, array) {
    //执行某些操作
});

下面是用原生js模拟实现的forEach() 方法。

if(!Array.prototype.forEach) {
    Array.prototype.forEach = function(fn, context) {
        var context = arguments[1];
        if(typeof fn !== "function") {
            throw new TypeError(fn + "is not a function");
        }

        for(var i = 0; i < this.length; i++) {
            fn.call(context, this[i], i, this);
        }
    };
}

相关文章

网友评论

      本文标题:用原生js实现forEach()方法

      本文链接:https://www.haomeiwen.com/subject/bblgvqtx.html