for in (ES5 标准)
遍历一个对象除 symbol 以外的可枚举属性
break
和continue
可以正常执行
return
不能被正常执行
副作用
for in 不应该迭代关注索引顺序的 Array
遍历数组时
- index 索引是
string
类型
- 遍历顺序可能是随机的
- 会遍历所有可枚举对象, 包括原型
for of (ES6 标准)
- 完美避开 for in 所有缺陷
- 可以遍历数组、类数组字符串以及任何可以迭代第对象(
map
,set
,DOM
), 但是不能遍历对象
- 支持解构
const persons = [
{ name: 'John Smith' },
{ name: 'Jane Doe' }
]
for (const { name } of persons) {
console.log(name);
}
- 与 forEach 不同的是, 它可以正确响应
break
、continue
和return
forEach
- 不能正确响应
break
、continue
return
结束当前循环
- 没有返回值