Symbol.iterator迭代器

8/20/2024 Javascript

# 模拟实现 for...of 遍历对象

const p = {
    name: 'april',
    age: 18,
}

Object.defineProperty(p, Symbol.iterator, {
    enumerable: false,
    configurable: false,
    writable: false,
    value: function () {
        const _this = this
        let nowIndex = -1
        let key = Object.keys(_this)
        return {
            next: function () {
                nowIndex++
                return {
                    value: _this[key[nowIndex]],
                    done: nowIndex + 1 > key.length,
                }
            },
        }
    },
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

# 模拟实现 for 循环

let students = {
    [Symbol.iterator]: function* () {
        for (let i = 0; i <= 100; i++) {
            yield i
        }
    },
}
for (const s of students) {
    console.log(s)
}
1
2
3
4
5
6
7
8
9
10
上次更新: 9/26/2024, 6:39:50 PM