forEach是ES5中操作数组的一种方法,用来遍历数组中的每一项;这个方法执行是没有返回值的,对原来数组也没有影响;
- 数组中有几项,那么传递进去的匿名回调函数就需要执行几次;
- 每一次执行匿名函数的时候,还给其传递了三个参数值:数组中的当前项item,当前项的索引index,原始数组input;
- 理论上这个方法是没有返回值的,仅仅是遍历数组中的每一项,不对原来数组进行修改;但是我们可以自己通过数组的索引来修改原来的数组;
forEach方法中的this是调用它的数组,匿名回调函数中的this默认是window,因此:
[].forEach(function(value,index,array){
//code something
});
等价于:
$.each([],function(index,value,array){
//code something
})
会发现,第1个和第2个参数正好是相反的,要注意了,不要记错了,后面类似的方法,例如$.map也是如此。
var arr = [1,2,3,4];
var res= arr.forEach(function(value,index,array){
array[index] = value*4;
});
console.log(arr); //结果为[4,8,12,16]
console.log(res); //undefined,因为forEach()没有返回值
var a = [1,2,5,7,3,6,9,0,8,4];
var a1 = [];
var sum = 0;
a.forEach((value,index,a) => {
sum += value;
a1[index] = value;
a[index] = sum;
});
console.log('a1:'+a1+'\na:'+a+'\nsum:'+sum);