循环语句 | for-in&&for-of的区别

for…of..

for…of用于遍历可迭代对象的元素,在可迭代对象上创建一个迭代循环,调用自定义迭代钩子的next()方法来遍历元素,是有序遍历

for…in..

for…in用于枚举对象中的属性(包括原型链上的可枚举属性),是无序遍历

面试题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
let o = {
name: 'Katrina',
age: 18,
};

Object.prototype.gender = 'female';

for (let key in o) {
console.log(key); // name age gender
};

// 根据打印结果可以看到 for...in枚举原型链上的属性,那么如何改进呢?使用hasOwnProperty
let o = {
name: 'Katrina',
age: 18,
};

Object.prototype.gender = 'female';
for (let key in o) {
if (o.hasOwnProperty(key)) {
console.log(key) // name age
}
};