本文主要和大家分享JS的数组遍历的常用方法实例,本文有三种方法,希望能帮助到大家。
第一种:for循环
for(var i=0 , len= arr.length ; i第二种:forEach
var arr=[12,14,15,17,18];var res=arr.forEach(function(item,index,input){ input[index]=item*10;});console.log(res); //undefinedconsole.log(arr); //会对原来的数组产生改变登录后复制
参数说明:item:数组中的当前项
index:当前项的索引
input:原始的数组input
重要说明:没有返回值(res还是无法返回新数组,且原数组也没有改变,因为input值没变)
var arr=[12,14,15,17,18];var res=arr.forEach(function(item,index,input){ return item*10;});console.log(res); //undefinedconsole.log(arr); //[12,14,15,17,18]没变登录后复制
其他说明:匿名函数的this指向Windows
如果匿名函数中对数组有修改,会修改到原数组
第三种:map
var arr=[12,14,15,17,18];var res=arr.map(function(item,index,input){ return item*10;});console.log(res); //[120,140,150,170,180]console.log(arr); //[12,14,15,17,18]登录后复制
参数说明:item:数组中的当前项
index:当前项的索引
input:原始的数组input
重要说明:有返回值 (要是不给返回值,res就是undefined,但res确实是个数组,只要改变input,原数组就会改变)
var arr=[12,14,15,17,18];var res=arr.map(function(item,index,input){ input[index]=item*10;});console.log(res); //[undefined, undefined, undefined, undefined, undefined]console.log(arr); //[120,140,150,170,180]登录后复制
其他说明:匿名函数的this指向Windows
如果匿名函数中对数组有修改,会修改到原数组
以上就是JS的数组遍历的常用方法实例的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2782642.html