1. 程式人生 > >算法-實現each遍歷多維數組(javascript)

算法-實現each遍歷多維數組(javascript)

算法

# 實現each遍歷多維數組
  <script type="text/javascript">
   
//   var arr=[1,2,3,4,[1,2,3,4]]
//   arr.forEach(function(item,index,array)){}
   var arr=[12,3,2,3,4,[3,2,4,1],[3,3,1,32,12,4,4,52]]
   
   Array.prototype.each=function(fn){
    try{
//     1、使用this.i,記錄當前遍歷元素的位置,單獨的作用域
     this.i || (this.i=0)
//     2、嚴謹判斷什麽時候使用each():
//     當數組長度大於0,且傳遞的參數必須為函數     
     if(this.length>0 && fn.constructor==Function){
//      遍歷數組,底層使用while,for,少用for in      
      
      while(this.i<this.length){
       var e=this[this.i]
//       判斷元素是否為數組
       if(e && e.constructor==Array){
//        如果元素為數組,則執行遞歸操作
        e.each(fn)
       }else{
//        如果元素為非數組,則把元素傳遞給fn函數,
//        傳遞參數(當前元素)給fn,並執行函數fn
        fn.call(null,e)
       }
       this.i++
      }
//      函數執行完成後,釋放內存,回收變量
      this.i=null
     }
    }catch(ex){
     //TODO handle the exception
    }
    
    return this
   }
   

   console.log(arr.each())
   
  </script>

算法-實現each遍歷多維數組(javascript)