Javascript Iterator Definition

Introduction

Any object that implements the Iterator interface can be used as an iterator.

The following example defines a Counter class to iterate a specific number of times:

class Counter {/* w  w  w. j av a2s . c  o m*/
    constructor(limit) {
        this.count = 1;
        this.limit = limit;
    }

    next() {
            if (this.count <= this.limit) {
                return {
                    done: false,
                    value: this.count++
                };
            } else {
                return {
                    done: true,
                    value: undefined
                };
            }
        }
        [Symbol.iterator]() {
            return this;
        }
}

let counter = new Counter(3);

for (let i of counter) {
    console.log(i);
}
// 1 
// 2 
// 3 

The Counter instance can be iterated only once:

for (let i of counter) {
    console.log(i);//from w  w w  . ja v a 2  s.  c  o  m
}
// 1 
// 2 
// 3  

for (let i of counter) {
    console.log(i);
}
// (nothing logged) 



PreviousNext

Related