1. 程式人生 > >Array each方法 遍歷多維數組

Array each方法 遍歷多維數組

const 循環數組 || each 操作 class while urn htm

<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script type="text/javascript">
			// 自己實現一個 Array each方法 遍歷多維數組
			 var arr=[1,2,3,[4,[5],[6]]];
			 Array.prototype.each=function(fn){
			 	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){
			 		 			// 直接做遞歸操作
			 		 			e.each(fn);
			 		 			
			 		 			
			 		 		}else{
			 		 			//如果不是數組 (那就是一個單個元素)
			 		 			//這個目的就是為了把數組的當前元素傳遞給fn函數 並讓函數執行
			 		 			fn .call(e,e);
			 		 		}
			 		 		this.i++ ;
			 		 	
			 		 	}
			 		 	this.i=null; //釋放內存 垃圾回收機制回收變量
			 		 	
			 		 }
			 	}catch(e){
			 		//TODO handle the exception
			 	}
			 	return this;
			 }
			 arr.each(function(item){
			 	alert(item);
			 })
			 
		</script>
	</head>
	<body>
	</body>
</html>

Array each方法 遍歷多維數組