for in
, for of
和forEach
三者都是循环时经常使用的,但是每个使用场景都是有轻微不同,接下来就进行一个对比
1.1 for…in…的作用
1.1.1 可枚举对象
const person = {
name: 'Lydia',
age: 21,
};
for (const item in person) {
console.log(item);
}
这个输出结果是: name age
对于这个结果可以简单理解为,对于对象object,使用for…in…循环是对对象的key值进行循环。
但是使用for…of…结果就不相同
const person = {
name: 'Lydia',
age: 21,
};
for (const item of person) {
console.log(item);
}
这个输出结果TypeError: person is not iterable
这个结果可以看出for…of…不能对对象进行循环
再看看forEach能怎么样?
const person = {
name: 'Lydia',
age: 21,
}
person.forEach((i) => {
console.log(i)
})
这个输出结果TypeError: person.forEach is not a function
这个结果可以看出forEach不能对对象进行遍历
1.1.2 可枚举数组
const arr = ['a','b','c']
for (const item in arr) {
console.log(item);
console.log(arr[item]);
}
这个输出结果为 0 ‘a’ 1 ‘b’ 2 ‘c’
这个结果看出使用for…in…是输