在 ECMAscript 中遍历数据有很多方法,首先就是最基本的 for 循环,它比较适用于去遍历普通的数组;然后就是 for ... in 它比较适合去遍历键值对;再有就是一些函数式的遍历方法,例如数组对象的 forEach 方法。这些各种各样的遍历数据的方式都有一定的局限性,所有 ES2015 它借鉴了很多其他的语言引入了一种全新的 for ... of 循环。这种循环方式以后会作为遍历所有数据结构的统一方式,换句话说只要明白 for ... of 内部的工作原理,就可以使用这种循环去遍历任何一种自定义的数据结构。
const arr = [100, 200, 300, 400];
for (const item of arr) {
console.log(item)
}
-
for ... of VS for ... in : 前者遍历的是数组的项、后者遍历的是数组的下标;
-
for ... of VS arr.forEach 方法:前者可以使用 break 终止循环、后者不可以,以前要实现终止遍历都是使用 arr.some() 、arr.every();
-
除了数据可以使用 for ... of 遍历以外,伪数组也可以使用 for ... of 进行遍历,比如 arguments 对象、dom 节点列表、set 对象、map 对象
const s = new Set(['foo', 'bar']); for (const item of s) { console.log(item) } // foo bar const m = new Map() m.set('foo', '123') m.set('bar', '456') for (const item of m) { console.log(item) } // ['foo', '123'] // ['bar', '456'] const obj = { foo: '123', bar: '456', } for (const item of obj) { console.log(item) } // obj is not iterable