1.for of
更多的是操作数组,如果操作的是对象会报错,作用是获取数组每一项中的值.类似于数组的forEach和map的第一个参数
const arr = [a,b,c];
for (let item of arr) {
console.log(item);
}
//输出结果
a
b
c
//同下
arr.forEach(item=>{
console.log(item)
})
//输出结果
a
b
c
2,for in
更多的是操作属性,只能遍历带有iterator接口的,例如Set,Map,String,Array,例如数组中的下标,对象的属性
const obj = {
a: 1,
b: 2,
c: 3
}
for (let item in obj) {
console.log(item);
}
//输出结果为对象的属性
a
b
c
//如果想要获取值可以使用.或者[]获取
for (let item in obj) {
console.log(obj[item]);
}
//输出结果为对象的属性
1
2
3