forEach方法:数组中的每个元素执行指定操作。
array1.forEach(callbackfn[, thisArg])
参数
| 参数 | 定义 |
| array1 | 必选。 一个数组对象。 |
| callbackfn | 必选。 最多可以接受三个参数的函数。 对于数组中的每个元素,forEach 都会调用callbackfn 函数一次。 |
| thisArg | 可选。 callbackfn 函数中的 this 关键字可引用的对象。 如果省略 thisArg,则 undefined将用作 this 值。 |
对于数组中出现的每个元素,forEach 方法都会调用 callbackfn 函数一次(采用升序索引顺序)。 将不会为数组中缺少的元素调用回调函数。
1.下面的示例阐释了 forEach 方法的用法。
js代码
function ShowResults(value, index, ar) {
document.write("value: " + value);
document.write(" index: " + index);
document.write("<br />");
}
// Create an array.
var letters = ['ab', 'cd', 'ef'];
// Call the ShowResults callback function for each
// array element.
letters.forEach(ShowResults);
// Output:
// value: ab index: 0
// value: cd index: 1
// value: ef index: 2
2.在下面的示例中,callbackfn 参数包含回调函数的代码。
js代码
// Create an array.
var numbers = [10, 11, 12];
// Call the addNumber callback function for each array element.
var sum = 0;
numbers.forEach(
function addNumber(value) { sum += value; }
);
document.write(sum);
// Output: 33
3.下面的示例阐释了 thisArg 参数的用法,该参数指定可对其引用 this 关键字的对象。
js代码
// Define the object that contains the callback function.
var obj = {
showResults: function(value, index) {
// Call calcSquare by using the this value.
var squared = this.calcSquare(value);
document.write("value: " + value);
document.write(" index: " + index);
document.write(" squared: " + squared);
document.write("<br />");
},
calcSquare: function(x) { return x * x }
};
// Define an array.
var numbers = [5, 6];
// Call the showResults callback function for each array element.
// The obj is the this value within the
// callback function.
numbers.forEach(obj.showResults, obj);
// Embed the callback function in the forEach statement.
// The obj argument is the this value within the obj object.
// The output is the same as for the previous statement.
numbers.forEach(function(value, index) { this.showResults(value, index) }, obj);
// Output:
// value: 5 index: 0 squared: 25
// value: 6 index: 1 squared: 36
// value: 5 index: 0 squared: 25
// value: 6 index: 1 squared: 36
5726

被折叠的 条评论
为什么被折叠?



