zoukankan      html  css  js  c++  java
  • 拓展 Array 方法

    为 Array 对象扩展了一个迭代器之后,就可以利用这个法代器进一步拓展 Array 的方法,使其能够完成更多的实用功能。

    Array.prototype.each = function( f ) {  //数组法代器,扩展 Array 原型方法 
        try{  //异常处理,避免因为不可预测的错误导致系统崩溃 
            this.i || ( this. i = 0 ); //定义临时变量,用来作为法代计数器 
            if( this.length > 0 && f.constructor == Function ) { 
                //如果数组长度大于 0并且参数为函数
                while( this.i < this.length ) { //遍历数组
                    var e = this[this.i]; //获取当前元素 
                    if( e && e.constructor == Array ) {  //如果元素存在,且为数组
                        e.each ( f ) ; //递归调用法代器 
                    }else{  //否则,在元素上调用参数函数,并把元素值传递给函数 
                        f.apply(e, [e]); 
                    }
                    this.i++;    //递加计数器
                }
                this.i = null;     //如果通历完毕,则清空计数器
            }
        }
        catch(err){       //捕捉以后
        }
        return this;      //返回当前数组
    }
    
    //调用该迭代器
    var a = [1, [2, [3, 4]]];
    var f = function( x ) { 
        alert(x);
    }
    a.each(f);     //调用迭代器,为每个元素执行一次函数传递
  • 相关阅读:
    特殊集合
    推箱子
    集合
    数组

    循环语句 练习题
    穷举与迭代
    循环语句
    练习题
    switch case
  • 原文地址:https://www.cnblogs.com/lanshu123/p/10566165.html
Copyright © 2011-2022 走看看