拓展 Array 方法

为 Array 对象扩展了一个迭代器之后,就可以利用这个法代器进一步拓展 Array 的方法,使其能够完成更多的实用功能。

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
Array.prototype.each = function( f ) {  //数组法代器,扩展 Array 原型方法 
try{ //异常处理,避免因为不可预测的错误导致系统崩溃
this.i || ( this. i = 0 ); //定义临时变量,用来作为法代计数器
if( this.length > 0 && f.constructor == Function ) {
//如果数组长度大于 0并且参数为函数
while( this.i < this.length ) { //遍历数组
var e = this[this.i]; //获取当前元素
if( e && e.constructor == Array ) { //如果元素存在,且为数组
e.each ( f ) ; //递归调用法代器
}else{ //否则,在元素上调用参数函数,并把元素值传递给函数
f.apply(e, [e]);
}
this.i++; //递加计数器
}
this.i = null; //如果通历完毕,则清空计数器
}
}
catch(err){ //捕捉以后
}
return this; //返回当前数组
}

//调用该迭代器
var a = [1, [2, [3, 4]]];
var f = function( x ) {
alert(x);
}
a.each(f); //调用迭代器,为每个元素执行一次函数传递

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×