loading

怎么让 for of 遍历对象

for of 遍历数组的时候,for of 会自动循环请求数组的迭代器,并自动使用这个迭代器遍历数组的值,而对象并不能使用for of来遍历。

  • 一般来说,使用 for in 遍历对象,返回键名;for of 遍历数组,返回值;因为 for in 会返回对象原型上的属性键名
  • for of 遍历对象的关键就是给对象添加迭代器和 next() 方法;
let index = 0;
let a = {
    name: 'wude',
    age: 11,
    [Symbol.iterator]:function(){
        console.log('调用了迭代器');
        return this;
    },
    next: function() {
        console.log('调用了next');
        return {
            value: this[arr[index++]],
            done: index < arr.length ? false :true
        };
    }
};
let arr = Object.keys(a);
for(let i of a){
    console.log(i);
};

// 调用了迭代器
// 调用了next
// wude
// 调用了next
// 11
// 调用了next
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
最近更新时间: 2022/09/28 16:26:36
最近更新
01
2023/07/03 00:00:00
02
2023/04/22 00:00:00
03
2023/02/16 00:00:00