先总结:
for in
适用于纯对象的遍历,并且只能输出可枚举属性forEach
适用于需要知道索引值的数组遍历,但是不能中断for of
适用于无需知道索引值的数组遍历,因为可以中断。另外对于其他字符串,类数组,类型数组的迭代,for of
也更适用
for...in
for in
是为遍历对象属性而构建的,它以任意顺序遍历一个对象的除Symbol
以外的可枚举属性,可用break
或者throw
跳出。
- 语法
for (variablename in object) { // 可枚举属性 // 注意: 不是可枚举属性 console.log(variablename); }
- 例子:
- 遍历对象
let obj = { name: 'xiaoming', age: 18 } for(let item in obj){ console.log(item) } // 输出:name age
- 遍历数组:返回数组的索引值
let arr = ['a', 'b', 'c']; for(let item in arr){ console.log(item) } // 输出: 0 1 2
- 需要注意的是,
for in
会遍历原型链的属性
Array.prototype.ufo = 'xiaoqiang'; let arr = ['a', 'b', 'c']; for(let item in arr){ console.log(item) } // 输出:0 1 2 ufo
for of
for of
语句在可迭代对象上创建一个迭代循环,调用自定义迭代钩子,并为每个不同属性的值执行语句(包括Array
、Map
、Set
、String
、TypedArray
、Argument
等,不包括Object)可用break
或者throw
跳出。
- 语法
for(variable of 可迭代对象){
// 操作语句
}
- 例子
let arr = ['a', 'b', 'c'] let obj = { name: '张三', age: 18, sex: '男' } for (let i of arr) { console.log(i) } // 输出 a b c for (let i of obj) { console.log(i) } // 报错 obj is not iterable (obj不是可迭代的)
for of与for in的不同
-
for...of
不像for...in
, 它不支持遍历普通对象,因为普通对象没有迭代器接口。但是可以通过Object.key()
去遍历迭代。 -
for...of
支持 迭代Unicode
字符串、set
及map
。 -
for...of
可以通过await
关键字每次迭代中等待异步任务
for await ( value in statcks ) {
//...
}
- 语法:
for (variable in object) {
// 在此执行代码
}