JS中的几种数组遍历

135 阅读1分钟

JS中的几种数组遍历

  1. for循环

  2. for in 索引遍历

  3. 数组.forEach方法

  4. for of 值遍历(ES6)

1.for循环

var team = ['a', 'b', 'c'];

for(var i=0; i<team.length; i++){

console.log(i, team[i]);

}

2.for in 索引遍历

var team = ['a', 'b', 'c'];

for(var i in team){

console.log(i, team[i]);

}

3.数组对象.forEach方法 内置Array数组对象的方法

//数组.forEach(function(v, k, arr){});

//forEach第一个参数 就是一个函数

//函数的参数: 第一个表示遍历到的值,第二个参数表示遍历到的下标,第三个参数是数组本身

//函数的形参,可以根据需要,使用一个,两个,三个都行


var team = ['a', 'b', 'c'];

team.forEach(function(v, k, arr){

console.log(v, k, arr);

});

team.forEach(function(v, k){

console.log(v, k);

});

team.forEach(function(v){

console.log(v);

});

4. for of 值遍历(ES6)

var team = ['a', 'b', 'c'];

for(var v of team){

console.log(v);

}

欢迎指正, 欢迎补充


End