遍历数组
-
for in返回数组的索引 -
for of返回数组的元素
const arr = [ 'a', 'b', 'c' ]
for (const i in obj) {
console.log(i) // 0 1 2
}
for (const i of obj) {
console.log(i) // a b c
}
遍历对象
-
for in返回对象的键 -
for of只可以遍历有iterator接口的数据结构的对象
如:ArrayMapSetStringargumentsNodelist
const obj = { a: 1, b: 2, c: 3 }
for (const key in obj) {
console.log(key) // a b c
}
for of与forEach
-
for of可以与breakcontinuereturn配合使用,即可以随时退出循环 - 而
forEach不可以