<%@ 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>My JSP 'test3.jsp' starting page</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"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <script src="js/jquery-2.1.1.min.js"></script> <script type="application/javascript"> //遍歷數組的每一項,只適合遍歷一維數組 // var array=[1,2,3,[4,[5]]]; // array.forEach(function(item,index,array){ // alert(item); // }); //本身實現一個能遍歷多維數組的Array each方法 var array2=[1,2,3,[4,[5,[6]]]]; Array.prototype.each=function(fn){ try{ //1.遍歷數組的每一項 this.i || (this.i=0); //嚴謹的判斷,何時進入條件 //當數組的長度大於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.apply(e,[e]); fn.call(e,e); } this.i++; } this.i=null; //使用完i回收垃圾 } }catch(ex){ alert("出錯"); } return this; } array2.each(function(item){ alert(item); }); </script> </head> <body> This is my JSP page. <br> </body> </html>