-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path020_oop4.htm
More file actions
63 lines (54 loc) · 1.87 KB
/
020_oop4.htm
File metadata and controls
63 lines (54 loc) · 1.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type=text/javascript charset=utf-8>
// Array each方法
// ECMA5 forEach 循环遍历数组的每一项(只适合遍历一维数组)
/*
var arr = [1,2,3,4,5];
arr.forEach(function(item , index , array){
alert(item);
});
*/
// 自己实现一个Array each方法 能遍历多维数组
var arr = [1,2,3,[4,[5,[6]]]]; // arr.length
Array.prototype.each = function(fn){
try{
//1 目的: 遍历数组的每一项 //计数器 记录当前遍历的元素位置
this.i || (this.i=0); //var i = 0 ;
//2 严谨的判断什么时候去走each核心方法
// 当数组的长度大于0的时候 && 传递的参数必须为函数
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 {
//如果不是数组 (那就是一个单个元素)
// 这的目的就是为了把数组的当前元素传递给fn函数 并让函数执行
//fn.apply(e,[e]);
fn.call(e,e);
}
this.i++ ;
}
this.i = null ; // 释放内存 垃圾回收机制回收变量
}
} catch(ex){
// do something
}
return this ;
}
arr.each(function(item){
alert(item);
});
</script>
</head>
<body>
</body>
</html>