for…in
for…in是为遍历对象属性而构建的,它以任意顺序遍历一个对象的除Symbol以外的可枚举属性,可用break或者throw跳出
语法:
for (variable in object) {
// 在此执行代码
}
例子:
let obj = {
name: '张三',
age: 18
}
for(let item in obj) {
console.log(item)
}
// 输出 name age
在JavaScript中,数组也是对象的一种,所以数组也是可以使用for…in遍历
let arr = ['a', 'b', 'c']
for(let item in arr) {
console.log(item)
}
// 输出 0 1 2
for…of
for…of语句在可迭代对象上创建一个迭代循环,调用自定义迭代钩子,并为每个不同属性的值执行语句(包括Array,Map,Set,String,TypedArray,arguments等等,不包括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…in还是for…of都是迭代一些东西。它们之间的主要区别在于它们的迭代方式
for…in语句以任意顺序迭代对象的可枚举属性
for…of语句遍历可迭代对象定义要迭代的数据
下面列出遍历Array时候,for…in和for…of的区别:
let arr = ['a', 'b', 'c']
Array.prototype.ufo = '张三'
for(let item in arr) {
console.log(item)
}
// 输出 0 1 2 ufo
for(let item of arr) {
console.log(item)
}
// 输出 a b c
上例,通过Array.prototype添加了ufo属性,由于继承和原型链,所以arr也继承了ufo属性,属于可枚举属性,所以for…in会遍历出来,而for…of则不会