对象和Iterator
对象想要被遍历
要做些改变
添加一个Symbol.iterator的属性。
1 class RangeIterator { 2 constructor(start, stop) { 3 this.value = start; 4 this.stop = stop; 5 } 6 7 [Symbol.iterator]() { return this; } 8 9 next() { 10 var value = this.value; 11 if (value < this.stop) { 12 this.value++; 13 return {done: false, value: value}; 14 } 15 return {done: true, value: undefined}; 16 } 17 } 18 19 function range(start, stop) { 20 return new RangeIterator(start, stop); 21 } 22 23 for (var value of range(0, 3)) { 24 console.log(value); // 0, 1, 2 25 }