Fork me on GitHub
杨小慧的博客

ES5中新增的Array方法——forEach()

forEachArray新方法中最基本的一个,用于遍历,循环。

forEach()方法

1. 语法:

1
array.forEach(callback[, thisObject])

2. 参数:

callback

用来测试每个元素的回调函数。callback被调用时传入三个参数:元素值,元素的索引,原数组。

thisObject

执行 callback 时使用的 this 值,为可选参数。如果省略该参数,则 callback 被调用时的 this 值,在非严格模式下为全局对象(浏览器中为window),在严格模式下传入 undefined。

3. 实例:

举例1:数组求和

1
2
3
4
5
6
// 只关心数组元素的值,可以编写只有一个参数的函数,额外的参数将忽略
var sum = 0;
[1,2,3,4].forEach(value) {
sum += value;
});
console.log(sum); // 10

举例2:每个数组元素的值自加1

1
2
3
4
5
// 关注数组元素的值,索引以及数组本身
[1,2,3,4].forEach(function (item, idx, arr) {
arr[idx] = item + 1;
});
console.log(arr); // [2,3,4,5]

举例3:指定this的值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var database = {
users: ["张含韵", "江一燕", "李小璐"],
sendEmail: function (user) {
if (this.isValidUser(user)) {
console.log("你好," + user);
} else {
console.log("抱歉,"+ user +",你不是本家人");
}
},
isValidUser: function (user) {
return /^张/.test(user); // 正则匹配张姓
}
};
// 给每个人发邮件
database.users.forEach(database.sendEmail, database); // 使用database代替this
// 结果:
// 你好,张含韵
// 抱歉,江一燕,你不是本家人
// 抱歉,李小璐,你不是本家

举例4:forEach不会遍历“空元素”

1
2
3
var arr = [1,,,3]; // 未赋值元素的值为undefined
console.log(arr.length); // 数组长度仍为4
arr.forEach(console.log); // 遍历结果只打印1和3

5. IE6-8兼容扩展

1
2
3
4
5
6
7
8
9
if (typeof Array.prototype.forEach != "function") {
Array.prototype.forEach = function (fn, context) {
for (var i = 0, len = this.length; i < len; i++) {
if (typeof fn === "function" && Object.prototype.hasOwnProperty.call(this, i)) {
fn.call(context, this[i], i, this); // fn.apply(context, [this[i], i, this]);
}
}
};
}

6. 终止循环

forEach()无法在所有元素都传递给调用的函数之前终止遍历,也就是说,没有像for循环中使用的相应的break语句。如果要提前终止,必须把forEach()方法放在一个try块中,并能抛出一个异常。如果forEach()调用的函数抛出foreach.break异常,循环会提前终止。

1
2
3
4
5
6
7
8
function foreach(a,f,t) {
try {a.forEach(f,t);}
catch(e) {
if(e === foreach.break) return;
else throw e;
}
}
foreach.break = new Error("StopIteration");
------本文结束感谢阅读------