ES6 自定义一个实现了Iterator接口的对象

参考资料

var obj = {
    data: [1,2,3,4,5],
        // 这里实际上就是去定义如何实现Iterator接口
    [Symbol.iterator](){
        const that = this;
        let index = 0;
        return {
            next(){
                if (index < that.data.length){
                    return {
                        done: false,
                        value: that.data[index++],
                    }

                } else {
                    return {
                        done: true,
                        value: undefined
                    }
                }
            }
        }
    }
}

console.log(...obj);

输出的结果就是 1 2 3 4 5

猜你喜欢

转载自www.cnblogs.com/westlin/p/11549858.html
今日推荐