1. js实现多维数组循环
<html>
<body>
打开控制台看结果
</body>
<script>
var arr = [
1,
2,
3,
[
4,
[
5,
6
],
[
7,
8
]
]
];
//自己实现一个each方法,遍历多维数据
Array.prototype.xeach = function(fn,ak){
try{
// 遍历数组的每一项,计数器,记录数组的每一项
this.i || (this.i = 0);
//严谨判断,什么时候去走each核心方法
//当数据的元素大于0 && 传递的参数必须为函数
if(this.length > 0 && fn.constructor == Function){
//循环遍历数据的每一项
while(this.i < this.length){
var e = this[this.i];
if(e && e.constructor == Array){
// 执行回调函数
console.log('第几级菜单==>'+ak)
ak++;
e.xeach(fn,ak);
}else{
//如果不是数组,那就是一个单个元素
//这的目的就是把数组的当前元素传递给fn函数,并让函数执行
// fn.apply(e,[e]);或者
fn.call(e,e);
}
this.i++;
}
}
//释放内存,垃圾回收机制回收变量
this.i = null;
}
catch(ex){
// do something
}
return this;
}
arr.xeach(function(item){
console.log(item);
},1)
</script>
</html>
## (JS中的call()方法和apply()方法用法总结)http://blog.csdn.net/ganyingxie123456/article/details/70855586