Javascript Iterator Create a Custom Iterator

Introduction

We can create custom iterators by providing a next method inside the object while keeping track of its current position.

let countdown = { 
     max: 3, /* ww w  .ja v  a2s  . c  o m*/
     [Symbol.iterator]() { 
         return this; 
     }, 
     next() { 
        if(this.max == undefined){ 
           this.max = max; 
        }else if(this.max > -1){ 
           return {value: this.max --}; 
        }else{ 
           return {done: true}; 
        } 
     } 
}; 

for (let i of countdown) { 
     console.log(i); 
} 



PreviousNext

Related