Javascript 中 数组遍历 forin和forof 的区别

定义一个数组

       let array = [1, 2, 3, 4];

       for (let a in array){
           console.log("遍历a的值 "+a+"”,数组中的值" + array[a])
       }

       for (let a of array){
           console.log("遍历a的值 "+a);
       }

  输出结果

       遍历a的值 0”,数组中的值1
       遍历a的值 1”,数组中的值2
       遍历a的值 2”,数组中的值3
       遍历a的值 3”,数组中的值4
       遍历a的值 1
       遍历a的值 2
       遍历a的值 3
       遍历a的值 4

  结论 forin 遍历的是索引,循环体内拿到的是索引值。和 普通 for i i递增一致。for of 遍历的是数组内的值,和索引无关

原文地址:https://www.cnblogs.com/munan56/p/12462872.html