Home > Web Front-end > JS Tutorial > body text

Share the example code of Iterator and iterator interface

零下一度
Release: 2017-06-24 14:41:48
Original
1663 people have browsed it

Iterator interface

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

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
  }
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template