码迷,mamicode.com
首页 > 其他好文 > 详细

forEach方法

时间:2018-09-04 23:28:00      阅读:242      评论:0      收藏:0      [点我收藏+]

标签:绑定   ocs   遍历数组   new   元素   OLE   不同   箭头   数组元素   

forEach 方法按升序为数组中含有效值的每一项执行一次callback 函数,那些已删除或者未初始化的项将被跳过(例如在稀疏数组上)。

callback 函数会被依次传入三个参数:

  • 数组当前项的值
  • 数组当前项的索引
  • 数组对象本身

如果给forEach传递了thisArg参数,当调用时,它将被传给callback 函数,作为它的this值。否则,将会传入 undefined 作为它的this值。callback函数最终可观察到this值,这取决于 函数观察到this的常用规则

示例

for 循环转换为 forEach

转换之前

const items = [‘item1‘, ‘item2‘, ‘item3‘];
const copy = [];

for (let i=0; i<items.length; i++) {
  copy.push(items[i])
}

转换之后

const items = [‘item1‘, ‘item2‘, ‘item3‘];
const copy = [];

items.forEach(function(item){
  copy.push(item)
});

打印出数组的内容

下面的代码会为每一个数组元素输出一行记录:

 1 function logArrayElements(element, index, array) {
 2     console.log("a[" + index + "] = " + element);
 3 }
 4 
 5 // 注意索引2被跳过了,因为在数组的这个位置没有项
 6 [2, 5, ,9].forEach(logArrayElements);
 7 
 8 // a[0] = 2
 9 // a[1] = 5
10 // a[3] = 9
11 
12 [2, 5,"" ,9].forEach(logArrayElements);
13 // a[0] = 2
14 // a[1] = 5
15 // a[2] = 
16 // a[3] = 9
17 
18 [2, 5, undefined ,9].forEach(logArrayElements);
19 // a[0] = 2
20 // a[1] = 5
21 // a[2] = undefined
22 // a[3] = 9
23 
24 
25 let xxx;
26 // undefined
27 
28 [2, 5, xxx ,9].forEach(logArrayElements);
29 // a[0] = 2
30 // a[1] = 5
31 // a[2] = undefined
32 // a[3] = 9

 

使用thisArg

举个勉强的例子,从每个数组中的元素值中更新一个对象的属性:

 1 function Counter() {
 2     this.sum = 0;
 3     this.count = 0;
 4 }
 5 
 6 Counter.prototype.add = function(array) {
 7     array.forEach(function(entry) {
 8         this.sum += entry;
 9         ++this.count;
10     }, this);
11     //console.log(this);
12 };
13 
14 var obj = new Counter();
15 obj.add([1, 3, 5, 7]);
16 
17 obj.count; 
18 // 4 === (1+1+1+1)
19 obj.sum;
20 // 16 === (1+3+5+7)

 

因为thisArg参数 (this) 传给了forEach(),每次调用时,它都被传给callback函数,作为它的this值。

注意:如果使用箭头函数表达式传入函数参数,thisArg 参数会被忽略,因为箭头函数在词法上绑定了this值。
 
 
小练习:
 1 // 练习1: 遍历数组中的值,并计算总和
 2 var numbers = [1,2,3,4,5];
 3 var sum = 0;
 4 
 5 function adder(number){
 6   sum += number;
 7 }
 8 
 9 numbers.forEach(adder);
10 console.log(sum); //15             
11 //练习2
12 [1, 2 ,3, 4].forEach(console.log); 
技术分享图片

 

forEach方法

标签:绑定   ocs   遍历数组   new   元素   OLE   不同   箭头   数组元素   

原文地址:https://www.cnblogs.com/gshao/p/9588911.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!