<!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>