遍历数组的方式

2018-09-11  本文已影响0人  Baowj

for循环

var arr = ["one","two","three",4,5,6];
for(var i = 0;i < arr.length;i++){
    console.log(arr[i]);
}
//输出
one
two
three
4
5
6

for...in

var arr = ["one","two","three",4,5,6];
for(var item in arr){                 //item是数组的下标,for...in循环的是key
    console.log(arr[item]+"/"+item);
}
//输出
one/0
two/1
three/2
4/3
5/4
6/5

for...of

var arr = ["one","two","three",4,5,6];
for(var item of arr){                 //item是定义的代表数组的变量,for...of循环的是value
    console.log(item);
}
//输出
one
two
three
4
5
6

forEach方法

var arr = [4,5,6];
//ele为数组中的元素,index为数组的下标
var res = arr.forEach(function(ele,index,arr){            
    ele*10;
 });
console.log(arr);          
console.log(res);    //--> undefined; 
//输出
[Log] [40, 50, 60] (3) (forEach.html, line 17)
[Log] undefined (forEach.html, line 18)

ps:没有赋值的元素不会在forEach中循环迭代出,forEach没有return值,

map方法

      var arr = [4,5,6];
        //ele为数组中的元素,index为数组的下标
        var res = arr.map(function(ele,index,arr){            
            return ele*10;

        });
        console.log(arr);          
        console.log(res); 
        //输出
       [Log] [4, 5, 6] (3) (forEach.html, line 17)
       [Log] [40, 50, 60] (3) (forEach.html, line 18)

ps:map有return值

上一篇 下一篇

猜你喜欢

热点阅读