ECMAScript5 中的数组方法 二十八

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 值。 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值