您的位置:首页 > Web前端 > JavaScript

javaScript,ECMA5,自定义each方法实现遍历多维数组

2017-02-27 10:25 393 查看
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>自定义each方法</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<script type="text/javascript" charset="utf-8">

//Array each 方法
//ECMA5 forEach 循环遍历数组的每一项
// 		var obj =[1,2,3,4,5,[6,[7]]];
// 		obj.forEach(function(item, index,array){
// 			alert(item);
// 		})
//自己实现一个Array each方法 能遍历多维数组
var obj =[1,2,3,4,5,[6,[7]]];
Array.prototype.each=function(fn){
try {
//目的:遍历数组的每一项//计数器 记录当前遍历的元素位置
this.i || (this.i=0);
//严谨的判断什么时候去走each核心方法
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{
//如果不是数组,就是单元素 直接调用
//var ob=true;//临时对象 回调时返回参数 但是需要回收 节省内存
//fn.apply(ob,[e]);//绑定一个作用域
fn.apply(e,[e]);//直接调用函数 把数组的当前元素传递给fn函数,并让函数执行
}
this.i++;
}
this.i=null;//释放内存 垃圾回收
}
} catch (e) {
// TODO: handle exception
}
return this;
}
obj.each(function(item){
alert(item);
});
</script>
</head>

<body>
This is my JSP page. <br>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息