遍历数组方式

for循环

      
        for (let i = 0; i < 9; i++) {
          console.log(i)
        }
      
    

for循环是最早也是最通用的一种数组遍历方式,缺点是不够简洁。当我们不想从头遍历数组时,for循环是唯一方式。

for...in

for...in语句以任意顺序遍历一个对象的除Symbol以外的可枚举属性。

      
        for (const key in someArray) {
          console.log(key);
        }
      
    

for...in不适合遍历数组:

forEach()

forEach()方法对数组的每个元素执行一次给定的函数。

      
        someArray.forEach((elem, index) => {
          console.log(elem, index);
        });
      
    

使用forEach()时要注意以下几点:

for...of

for...of语句在可迭代对象上创建一个迭代循环,并执行语句。对于数组,for...of常是最好的选择。

      
        for (const elem of someArray) {
          console.log(elem);
        }
      
    

示例:

      
        let iterable = [10, 20, 30];

        // 遍历数组索引
        for (const index of iterable.keys()) {
          console.log(index);
        }
        // 0
        // 1
        // 2

        // 遍历数组索引和值
        for (const [index, value] of iterable.entries()) {
          console.log(index, value);
        }
        // 0, 10
        // 1, 20
        // 2, 30
      
    

使用for...of循环数组有几点好处:

References

https://2ality.com/2021/01/looping-over-arrays.html

https://stackoverflow.com/questions/500504/why-is-using-for-in-for-array-iteration-a-bad-idea

https://www.cnblogs.com/goloving/p/9180588.html

https://my.oschina.net/u/4593024/blog/4817930

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach