(ES6) ES6 (2016)

Iterator (IT301)

   1:  class Range {
   2:      constructor(start, end, step = 1) {
   3:          this.start = start;
   4:          this.end = end;
   5:          this.step = step;
   6:      }
   7:  
   8:      *[Symbol.iterator]() {
   9:          let current = this.start;
  10:          while (current <= this.end) {
  11:              yield current;
  12:              current += this.step;
  13:          }
  14:      }
  15:  }
  16:  
  17:  const range = new Range(1, 5);
  18:  for (const num of range) {
  19:      console.log(num); // 1, 2, 3, 4, 5
  20:  }
  21:  
  22:  console.log([...new Range(10, 15, 2)]); // [10, 12, 14]



Range Generator

1
2
3
4
5
[ 10, 12, 14 ]





Iterator context:






ES6 context:



Comments ( )
Link to this page: http://www.vb-net.com/JavascriptES6/IT301.htm
< THANKS ME>