js 实现 each 遍历方法

var arr = [1,2,3,[4,5,[6,7,[8]]]];
    
    Array.prototype.each = function (fn) {
        try {
            this.i || (this.i = 0);         // count 计数器 ,记录当前遍历的元素的位置
            // 严谨的判断什么时候走 核心的 each 方法
            // 条件 : 当数组长度大于 0 ,并且传递的参数为函数时
            if(this.length > 0 && fn.constructor == Function){
                // 循环遍历数组中的每一项
                while( this.i < this.length ){
                    // 获取数组中的每一项
                    var e = this[this.i];
                    // 如果获取的当前元素是一个 数组,则进行递归操作
                    if(e && e.constructor == Array){
                        e.each(fn)
                    }
                    // 如果获取的当前元素不是一个数组,则把数组的当前元素传递给 fn ,并且让 fn 执行
                    else {
                        fn.call(e,e)
                    }
                    this.i++;
                }
                this.i = null;            // 释放内存,等待垃圾回收机制回收
            }
        }
        catch (ex){
        }
    }
    
    arr.each(function (item) {
        alert(item)
    })

 

posted @ 2017-11-07 16:44  linfang.zhou  阅读(2296)  评论(0编辑  收藏  举报