ES6--Iterator和for...of循环

Iterator

{
    let arr=['hello','world'];
    let map=arr[Symbol.iterator]();
    console.log(map.next())
    console.log(map.next())
    console.log(map.next())
    //{value: "hello", done: false}
    //{value: "world", done: false}
    //{value: undefined, done: true}
}
{
    let obj={
        start:[1,3,2],
        end:[7,9,8],
        [Symbol.iterator](){
            let self=this;
            let index=0;
            let arr=self.start.concat(self.end);
            let len=arr.length;
            return {
               next(){
                   if(index<len){
                       return{
                           value:arr[index],
                           done:false
                       }
                   }else{
                       return{
                           value:arr[index++],
                           done:true
                       }
                   }
               }
            }
        }
    }
    for(let key of obj){
        console.log(key)
    }

}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容