数组遍历

方法

for (let i=0; i<arr.length; i++) — 运行得最快,可兼容旧版本浏览器。

for (let item of arr) — 现代语法,只能访问 items。

for (let i in arr) — 永远不要用这个。

案例

for..in

Array.prototype.flatten = () => {};
let arr = ['a', 'b', 'c'];
for (let key in arr) {
  console.log(arr[key]); // 注意这里的差别
}

输出:
a
b
c
() => {}

flatten 方法作为可枚举属性被遍历输出。

for..of

Array.prototype.flatten = () => {};
let arr = ['a', 'b', 'c'];
for (let key of arr) {
  console.log(key); // 注意这里的差别
}

输出:
a
b
c

参考

3 Reasons Why You Shouldn’t Use “for…in” Array Iterations in JavaScript

© 2022  Arvin Xiang
Built with ❤️ by myself