封装一个迭代器函数,使其既能遍历数组又能遍历对象

Object.prototype.myEach = function(fn) {
        // 区分数组和对象
        if(Array.isArray(this)) {
            // 数组
            for(var i = 0; i < this.length; i++) {
                fn(this[i], i, this);
            }
        }else {
            // 对象
            for(var i in this) {
                fn(this[i], i, this);
            }
        }
    };

    // 手动配置枚举性为false
    Object.defineProperty(Object.prototype, 'myEach', {
        enumerable: false,
    });
    
    // 遍历对象
    var obj = {a: 11, b: 22, c: 33};
    obj.myEach(function(value, index, obj) {
        console.log(value, index, obj);
    })
    // 遍历数组
    var arr = [1, 3, 4, 5];
    arr.myEach(function(value, index, arr) {
        console.log(value, index, arr);
    });

猜你喜欢

转载自www.cnblogs.com/yess/p/12160590.html