<!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>js遍歷多維數組</title> </head> <body> <script> //實現一個Array each方法,實現遍歷多維數組 var arr = [1,2,3,[4,5,[6,7]]]; //arr.length Array.prototype.each = function(fn){ try{ //1、目的 遍歷數組的每一項 //計數器 記錄當前遍歷的元素位置 this.i ||(this.i = 0); //2、判斷什么時候使用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); }else{ //如果不是數組(那就是一個單個元素) //把數組的當前元素傳遞給fn函數,並且讓函數執行 fn.call(e,e); } this.i++ } this.i == null; //釋放內存,垃圾回收機制回收變量 } }catch(err){ //do something } return this; } arr.each(function(item){ console.log(item); }) </script> </body> </html>