Javascript Symbol's iterator enables objects to support for..of traversal

First, let's take an array as an example. We need to know the principle of iterator iteration, that is, why it can support a loop syntax similar to for....of.

The principle of iterator traversing objects, look at the following code, we found the iterator, the whole process is very similar to the process of for...of, except that instead of looping, we call the iterator.next() one at a time 
const arr1=[1,2,3,4,5];
let ite=arr1[Symbol.iterator](); //重要的是这个迭代器
console.log(ite.next())//{ value: 1, done: false }
console.log(ite.next())//{ value: 2, done: false }
console.log(ite.next())//{ value: 3, done: false }
console.log(ite.next())//{ value: 4, done: false }
console.log(ite.next())//{ value: 5, done: false }
console.log(ite.next())//{ value: undefined, done: true }

Iteration principle: implement the iterator method of the object, [Symbol.iterator]    

Next, we let our own objects support for....of syntax by implementing iterators. Code 1 and code are two implementations

First implementation:

class ClassStudentList {
    stus = ["张三", "李四", "王五", "陈六"];
    #index = 0;

    constructor() {
    }
    //迭代器实现  用于支持for....of
    [Symbol.iterator]() {
        let $this = this;
        return{
            next:()=>{
                if ($this.#index < $this.stus.length) {
                    const ret = {value: $this.stus[$this.#index], done: false};
                    $this.#index++;
                    return ret;
                } else {
                    return {value: undefined, done: true};
                }
            }
        };
    }
}

//创建对象
let classInfo=new ClassStudentList();
//遍历对象
for(let stu of classInfo){
    console.log(stu)
}

Second implementation:

class ClassStudentList {
    stus = ["张三", "李四", "王五", "陈六"];
    #index = 0;

    constructor() {
    }
    //迭代器实现 function*()实现  用于支持for....of
    [Symbol.iterator]=function *() {
        let $this = this;
        for(let v of $this.stus){
            yield v;
        }
    }
}

//创建对象
let classInfo=new ClassStudentList();
//遍历对象
for(let stu of classInfo){
    console.log(stu)
}

result output

 

Guess you like

Origin blog.csdn.net/yue7603835/article/details/122254687