Home  >  Article  >  Web Front-end  >  Share the example code of Iterator and iterator interface

Share the example code of Iterator and iterator interface

零下一度
零下一度Original
2017-06-24 14:41:481654browse

Iterator interface

{
  let arr=['hello','world'];
  let map=arr[Symbol.iterator]();//数组实现了iterator接口
  console.log(map.next());
  console.log(map.next());
  console.log(map.next());
}

The output result is as follows:

Customized iterator interface

{
  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);//输出1,3,2,7,9,8可以证明  obj实现了iterator接口  可以使用for of
  }
}

The above is the detailed content of Share the example code of Iterator and iterator interface. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn