首页  >  文章  >  web前端  >  JS的数组遍历的常用方法实例

JS的数组遍历的常用方法实例

韦小宝
韦小宝原创
2018-03-14 18:47:481309浏览

本文主要和大家分享JS的数组遍历的常用方法实例,本文有三种方法,希望能帮助到大家。

第一种:for循环

for(var i=0 , len= arr.length ; i<len ; i++){  代码块 }

第二种:forEach

var arr=[12,14,15,17,18];
var res=arr.forEach(function(item,index,input){
   input[index]=item*10;
});
console.log(res);     //undefined
console.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);     //undefined
console.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的数组遍历的常用方法实例的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn