数组的遍历

  1. 我们最常用的遍历:for循环
let arr = [1,2,3,4,5,6];
for(let i = 0; i < arr.length; i++){
  console.log(arr[i]);  
} // 1 2 3 4 5 6

     2.for-in 遍历数组

let arr = [1,2,3,4,5,6];
for(let i in arr){
  console.log(i);  
}
// 0  1 2 3 4 5

注意:些方式主要迭代的是键。可以通过键来找到相应的数组元素。

    3. 通过for-of 遍历数组

 

let arr = [1,2,3,4,5,6];
for(let i of arr){
 console.log(i);
}
// 1 2 3 4 5 6 

注意:这里直接迭代的值。

  4.forEach遍历数组(涉及回调函数)

let arr = [1,2,3,4,5,6];
let i = arr.forEach(function(item){
   console.log(item); 
})

  5.使用迭代器进行遍历(ES6新增)

  • keys()
    • 得到的是可迭代元素的键;
  • values()
    • 得到的是可迭代元素的值;
  • entries()
    • 得到的是可迭代元素的键和值。

注意:数组里面无法使用values()方法

还可以发现在数组里面,keys()和entries()一般用于for-of中。

let arr = [1,2,3,4,5];
for(let i of arr.keys()){
 console.log(i);
}
// 0 1 2 3 4 
let arr = [1,2,3,4,5];
for(let i of arr.entries()){
 console.log(i);
}
// [0,1][1,2],[2,3],[3,4],[4,5]

在遍历中,for-of 和for循环是最常用的了,ES6新增的几个迭代器也是相当好用。有时间的话,可以在这方面更加深入的了解下。

原文地址:https://www.cnblogs.com/smuwgeg/p/9655900.html