遍历多维数组

遍历多维数组

  • 遍历一维数组(Array each方法)

    1
    2
    3
    4
    var arr = [1,2,3,4,5];
    arr.forEach(function(item,index,array){
    alert(item); //1 2 3 4 5
    });
  • 自己实现一个Array each方法,能遍历多维数组

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    var arr = [1,2,3,[4,[5,[6]]]]
    Array.prototype.each = function(fn) {
    try{
    //1.遍历数组的每一项
    this.i || (this.i = 0); //初始化i(减少声明,ES5)
    //2.判断什么时候走核心代码
    if(this.length>0 && fn.constructor === Function){
    //遍历
    while(this.i < this.length){ //while循环的范围
    //获取数组的每一项
    var e = this[this.i];
    //如果当前元素获取到了,并且当前元素是一个数组
    if(e && e.constructor === Array){
    //递归
    e.each(fn);
    }else{
    //如果不是数组,即就是元素
    //将数组元素传递给fn
    fn.call(e,e);
    }
    this.i++
    }
    this.i = null; //释放内存 垃圾回收机制
    }
    }catch(ex){
    //do someting
    }
    return this;
    }

    arr.each(function(item){
    console.log(item); // 1 2 3 4 5 6
    })