您好,欢迎来到纷纭教育。
搜索
您的当前位置:首页JS的数组遍历的常用方法实例

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

来源:纷纭教育


本文主要和大家分享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

如果匿名函数中对数组有修改,会修改到原数组

Copyright © 2019- fenyunshixun.cn 版权所有 湘ICP备2023022495号-9

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务