数组迭代

数组法代是一件很重要的操作,在 ECMAScript 5 之前主要使用 for 语句实现,这种方式不是很方便, 为此 ECMAScript 5 新增了 5 个与迭代相关的方法。

1.forEach:为数组中的每个元素调用定义的回调函数。

2.every:检查定义的回调函数如果每一项都返回true,则返回 true。

3.some:检查定义的回调函数如果任意一项返回true。返回 true。

4.map:对数组的每个元素调用定义的回调函数,并返回包含结果的数组。

5.filter:对数组的每个元素调用定义的回调函数,并返回回调函数为其返回 true 的值的数组。 具体说明如下。

reduce/reduceRight

使用 reduce 和 reduceRight 方法可以汇总数组元素的值,具体用法如下:

reduce

1
2
3
4
5
6
function appendCurrent (previousValue, currentValue) {
return previousValue + "::" + currentValue;
}
var elements = ["abc", "def", 123, 456];
var result = elements.reduce(appendCurrent);
document.write(result); //abc::def::123::456

拓展 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); //调用迭代器,为每个元素执行一次函数传递

call/apply/bind

使用 call() 和 apply()

call 和 apply是 Function 对象的原型方法,它们能够将特定函数当作一个方法绑定到指定对象上并进行调用。具体用法如下:

1
2
function.call(thisobj, args... ) 
function.apply(thisobj, args)

使用 arguments 对象

arguments 对象表示参数集合,它是一个伪类数组,拥有与数组相似的结构,可以通过数组下标的形式访问函数实参值,但是没有基础 Array 的原型方法

Your browser is out-of-date!

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

×