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

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


猜你喜欢

转载自blog.csdn.net/shirley_linxiaojia/article/details/79546210