Iterator(迭代器)接口數組
{ let arr=['hello','world']; let map=arr[Symbol.iterator]();//數組實現了iterator接口 console.log(map.next()); console.log(map.next()); console.log(map.next()); }
輸出結果以下:this
自定義iterator接口spa
{ 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 } }