首页 > 编程语言 > 详细

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

时间:2020-01-07 14:13:35      阅读:108      评论:0      收藏:0      [点我收藏+]
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);
    });

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

原文:https://www.cnblogs.com/yess/p/12160590.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!