Array原型链添加“遍历”方法

<script>
        //1.在我们之前的项目里向原型链中集成方法时大多代码分析不严密,有时间我在这里会做详细分析;
        Array.prototype.each = function(fn) {
            try {
                this.i || (this.i = 0);
                //在这里,fn.constructor === Function保证了输入的构造类型
                if (this.length > 0 && fn.constructor === Function) {
                    while (this.i < this.length) {
                        var tmpEach = this[this.i];
                        //tmpEach.constructor === Array 保证了递归时的构造类型
                        if (tmpEach && tmpEach.constructor === Array) {
                            tmpEach.each(fn);
                        } else {
                            fn(tmpEach);
                        }
                        this.i ++;
                    }
                }
            } catch (ex) {

            }
            return this;
        }


        var v=[1,2,3,[4,5,[6,7]]];
        v.each(function(item){
            alert(item);
        });
    </script>

 

posted @ 2015-05-31 13:54  soft.push("zzq")  Views(444)  Comments(0)    收藏  举报