js 的 forEach()函数

1.修改forEach回调函数中value参数,不会改变原数组

 1 var array=[1,2,3];
 2 //Array在ES5新增的方法中,参数都是function类型,默认有传参,forEach方法中的function回调支持3个参数,第1个是遍历的数组内容;第2个是对应的数组索引,第3个是数组本身
 3 array.forEach(function(value,index,data){
 4     ++value;//可以看出改变value的值,数组本身是没有改变的
 5     console.log("value:",value,"index:",index,"data:",data);
 6     //输出结果
 7     // value: 2 index: 0 data: (3) [1, 2, 3]
 8     // value: 3 index: 1 data: (3) [1, 2, 3]
 9     // value: 4 index: 2 data: (3) [1, 2, 3]
10 
11 });
12 console.log(array,"array");
13 //输出结果
14 // [1, 2, 3] "array"

2.对forEach回调函数的数组参数操作,原数组改变

1 var array=[1,2,3];
2 array.forEach(function(value,index,data){
3     ++value;
4     data.push(value);
5 });
6 console.log(array,"array");
7 // [1, 2, 3, 2, 3, 4] "array"

3.forEach函数是没有返回值的

 

1 var array=[1,2,3];
2 var newArray=array.forEach(function(value,index,data){
3 
4 });
5 console.log("newArray:",newArray);
6 //newArray: undefined

 

posted on 2018-12-16 00:04  绅士狼  阅读(5597)  评论(0编辑  收藏  举报

导航