码迷,mamicode.com
首页 > Web开发 > 详细

js 的 forEach()函数

时间:2018-12-16 00:54:53      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:结果   ons   index   log   push   console   类型   输出   col   

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

 

js 的 forEach()函数

标签:结果   ons   index   log   push   console   类型   输出   col   

原文地址:https://www.cnblogs.com/gentrywolf/p/10125472.html

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