Home > Article > Web Front-end > Share the example code of Iterator and iterator interface
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!