首页 > 代码库 > Iterator和for...of循环

Iterator和for...of循环

 1 var Items={
 2 [Symbol("random") ]: "items",
 3     _items:[{"n":"a"},{"n":"b"},{"n":"c"}],
 4     _num:0,
 5     [Symbol.iterator](){return this;},
 6     next(){
 7     return this._num>this._items.length-1?{done: true, value: undefined}:{done: false, value:this._items[this._num++] };
 8 },
 9 show(){
10   for (let item of this) {
11     console.log(item.n);
12   }
13 }
14 }
15 
16  
17 Items._num=0;
18 var item,iterator=Items[Symbol.iterator]();
19 while(!(item=iterator.next()).done){
20   console.log(item.value.n);
21 }

扩展运算符(...)也会调用默认的iterator接口。

var str = ‘hello‘;[...str] // [‘h‘,‘e‘,‘l‘,‘l‘,‘o‘]
let arr = [‘b‘, ‘c‘]; [‘a‘, ...arr, ‘d‘]// [‘a‘, ‘b‘, ‘c‘, ‘d‘]

解构赋值

let set = new Set().add(‘a‘).add(‘b‘).add(‘c‘);
let [x,y] = set;// x=‘a‘; y=‘b‘
let [first, ...rest] = set;
// first=‘a‘; rest=[‘b‘,‘c‘] 

yield*后面跟的是一个可遍历的结构,它会调用该结构的遍历器接口。

Items[Symbol.iterator]=function*() {
    for(var i=0;i<=this._items.length-1;i++) {
      this._items[i].n+="_";
      yield this._items[i];
    }
}
Items.show();

 

 

Iterator和for...of循环