实现数组的 forEach 方法

数组的 forEach 方法用来遍历数组,没有返回值。

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

arr.forEach((item, index, arr) => {
    console.log(index + ':' + item, arr);
})


0:1 (5) [1, 2, 3, 4, 5]
1:2 (5) [1, 2, 3, 4, 5]
2:3 (5) [1, 2, 3, 4, 5]
3:4 (5) [1, 2, 3, 4, 5]
4:5 (5) [1, 2, 3, 4, 5]

IE中的Array类型没有forEach()方法,那我们就来实现一个 forEach 方法。

第一版本

if (!Array.prototype.forEach1) {
    Array.prototype.forEach1 = function (callback, thisArg) {
        var _this, index;
        if (!Array.isArray(this)) {
            throw new TypeError("只能对数组使用forEach方法");
        }
        if (Object.prototype.toString.call(callback) != "[object Function]") {
            throw new TypeError('callback 必须是函数');
        }
        if (thisArg) {
            _this = thisArg;
        }
        for (index = 0; index < this.length; index++) {
            callback.call(_this, this[index], index, this);
        }
    }
}

但是对于疏松数组,arr = [ , , , , ,] 来使用 forEach 的话是得不到结果的。像我们上面使用 length 来循环,是会打印出 undefined 的 , arr[i] 找不到会返回 undefined。

所以我们需要改一改。

第二版。

if (!Array.prototype.froEach) {
    Array.prototype.froEach = function(callback, thisArg) {
        let _this, k = 0;
        if (!Array.isArray(this)) {
            throw new TypeError("只能对数组使用forEach方法");
        }
        var O = Object(this);
        var len = this.length;
        if (Object.prototype.toString.call(callback) != "[object Function]") {
            throw new TypeError('callback 必须是函数');
        }
        if (thisArg) {
            _this = thisArg;
        }
        while (k < len) {
            var kValue;
            if (k in O) {
                kValue = O[k];
                callback.call(T, kValue, k, O);
            }
            k++;
        }
    };
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值