ES5新增了5个迭代方法: every()、filter()、forEach()、map()、some() 。每个方法都接收两个参数: 要在每一项上运行的函数 和 (可选的)运行该函数的作用域对象 。
array1.forEach(callbackfn[, thisArg])
array1 | 必选。一个数组对象。 |
callbackfn | 必选。最多可以接受三个参数的函数。对于数组中的每个元素,forEach 都会调用 callbackfn 函数一次。 |
thisArg | 可选。 callbackfn 函数中的 this 关键字可引用的对象。如果省略 thisArg,则 undefined 将用作 this 值。 |
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
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
// 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
array1.map(callbackfn[, thisArg]) 对数组的每个元素调用定义的回调函数并返回包含结果的数组。
array1 | 必选。 一个数组对象。 |
callbackfn | 必选。 最多可以接受三个参数的函数。 对于数组中的每个元素,map 方法都会调用 callbackfn 函数一次。 |
thisArg | 可选。 callbackfn 函数中的 this 关键字可引用的对象。 如果省略 thisArg,则 undefined 将用作 this 值。 |