for-of只能从0开始吗

91 阅读1分钟

for-of是一个js里常用的迭代器。 在我们使用for(const x of Y)这个迭代器时似乎默认从0开始。
然而如果熟悉迭代器的底层实现我们也能让他从任意数开始。
符号Symbol.iterator是实现迭代器api的函数。

class Emitter{
    constructor(max){//构造器将传入最大参数设定保存
        this.max = max;
        this.index = 0;
    }
    *[Symbol.iterator](){//迭代器逻辑实现部分
        while(this.index<this.max)
            yield this.index++;
    }
}

function Itreator(max){
    let c = new Emitter(max);
    for (const X of c){
        console.log(X);
    }
}
b(5);