一、迭代功能是什么?

可迭代对象, 需要具备 Symbol.iteratornext 这两个函数,即可用 for...of 进行迭代。譬如:String、Array、TypedArray、Map 和 Set,都是可迭代对象。

var myIterator = {
    next: function() {
        // ...
    },
    [Symbol.iterator]: function() { return this }
}

二、怎么用?
1、转换 class 为迭代对象
<!DOCTYPE html>
<html lang='zh-CN'>

<head>
    <meta charset="utf-8">
    <title>Symbol</title>
    <script>
        class SimpleClass {
            constructor(data) {
                this.data = data
            }

            [Symbol.iterator]() {
                let index = 0;
                return {
                    next: () => {
                        if (index < this.data.length) {
                            return { value: this.data[index++], done: false }
                        } else {
                            return { done: true }
                        }
                    }
                }
            }
        }

        const simple = new SimpleClass([1, 2, 3, 4, 5])

        for (const val of simple) {
            console.log(val)   //'1' '2' '3' '4' '5'
        }

    </script>
</head>

<body>
    <h1>Symbol : 打开 Console 看结果!</h1>
</body>

</html>

2、转换 object 为迭代对象
<!DOCTYPE html>
<html lang='zh-CN'>

<head>
    <meta charset="utf-8">
    <title>Symbol</title>
    <script>
        let SimpleClass = {
            data: [1, 2, 3, 4, 5],
            [Symbol.iterator]() {
                let index = 0;
                return {
                    next: () => {
                        if (index < this.data.length) {
                            return { value: this.data[index++], done: false }
                        } else {
                            return { done: true }
                        }
                    }
                }
            }
        }

        for (const val of SimpleClass) {
            console.log(val)   //'1' '2' '3' '4' '5'
        }

    </script>
</head>

<body>
    <h1>Symbol : 打开 Console 看结果!</h1>
</body>

</html>

三、参考文章

Learn_anything
7 声望0 粉丝

收集互联网优质资源!