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

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


第四种:findIndex

arrayObj.findIndex(callbackfn [, thisArg]);

arrayObj

必需。数组对象。

callbackfn

必需。用于测试数组中的每个元素的回调函数。

thisArg

可选。指定回调函数中的 this 对象。如果未指定,则未定义 this 对象

对于数组中的每个元素,findIndex 方法都会调用一次回调函数(采用升序索引顺序),直到有元素返回 true只要有一个元素返回 true,findIndex 立即返回该返回 true 的元素的索引值。如果数组中没有任何元素返回 true,则 findIndex 返回 -1。

findIndex 不会改变数组对象。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值