for...in、for...of

Martin
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// for...in可以遍历数组和对象 遍历的项是数组或对象的key值
// object/array
const object = {
name: 'xiaoguo',
age: '20'
}
const array = ['a', 'b']
for (key in object) {
console.log(key)
}
// name
// age
for (key in array) {
console.log(key)
}
// 0
// 1

// for..of 只能遍历(具有可迭代对象iterator接口)数组,无法遍历对象
// 遍历的项是可迭代对象的值
// 如果需要遍历对象则需要在Object.keys(object)
for (item of array) {
console.log(item)
}
// a
// b
for (item of Object.keys(object)) {
console.log(item)
}
// name
// age