最近更新
阅读排行
关注本站

JS中的Array.forEach()方法

阅读:9180 次   编辑日期:2015-06-29

目录:

概述:

前一段时间面试被问到了ECMA5,很少自己去专门看,正好这段时间比较清闲,简单的看了看,接下来的几次文章简单的总结一下常用的,今天说说--Array.forEach() 。

Array.forEach()方法

Array.forEach 函数接受一个参数,这个参数应该是一个函数,在这个方法里面能把数组里面的每一个元素都执行一遍。
Array.forEach 函数接受的这个函数中,接受三个参数:正在被访问的特定元素、该元素的索引、以及数组本身。
注意:由于每次运行一个独立函数的开销,这个方法比对等的 for 循环慢得多。对于每个步骤,都将创建和销毁一个新的执行上下文,然后另一个级别被添加到作用域链(scope chain)。这些开销将累积起来。 注意:由于每次运行一个独立函数的开销,这个方法比对等的 for 循环慢得多。对于每个步骤,都将创建和销毁一个新的执行上下文,然后另一个级别被添加到作用域链(scope chain)。这些开销将累积起来。
示例如下:
   var arr = [8, 10, 13, 10, 8, 1, 5];
    function logger(element, index, array) {
        console.log("The value of the element at index " + index + " is " + element);
    }
    arr.forEach(logger);
>>>The value of the element at index 0 is 8
>>>The value of the element at index 1 is 10
>>>The value of the element at index 2 is 13
>>>The value of the element at index 3 is 10
>>>The value of the element at index 4 is 8
>>>The value of the element at index 5 is 1
>>>The value of the element at index 6 is 5
将本篇文章分享到:
top