Javascript - Iterator

About

In Javascript, an iterator is an iterator

Interface

An object has an iterator when it has:

  • a property named Symbol.iterator that return an object that implement the iterator interface. ie with:
    • a next function that returns an object called the IteratorResult with the following properties:
      • value - the returned value
      • done - a boolean that return true when this is no more element to return ( - if any.
    • [optional] a return function that returns the same IteratorResult than the next function. This function is called when:
      • the iteration reaches the last value,
      • or is stopped by a break

Example

How to create an iterator

var Fib = {
 [Symbol.iterator]() {
     var n1 = 1, n2 = 1;
     return {
         next() {
             var current = n2;
             n2 = n1;
             n1 = n1 + current;
             return { value: current, done: false };
         },
         return(v) {
             console.log('Done');
             return { value: v, done: true };
         }
     };
  }
};
for (var v of Fib) {
    console.log( v );
    if (v > 50) break;
}

How to read an iterator

Example with FormData

  • Building the iterator object
let formData = new FormData();
formData.append('username', 'Foo');
formData.append('age', '10');

For

The For over the object implementing an iterator

console.log("For loop");
for (let entry of formData) {
    console.log( entry );
}

While

The while iteration over the iterator

console.log("While loop");
let it = formData.entries();
let result = it.next();
while (!result.done) {
 console.log(result.value); 
 result = it.next();
}

Foreach

The foreach iteration over the iterator

console.log("For Each");
// value and key should be inverted
formData.forEach((value, key)=>{
 console.log(key+":"+value);  
})

Result

Documentation / Reference





Discover More
How to create and manipulate an URL in Javascript? (Browser URL Object)

This article shows you how to get and manipulate an URL with Javascript. URL You can manipulate an URL with the URL web API object Build an URL object Print a URL properties (...host, hostname,...)...
Formdata Browser Devtool
How to use FormData and send multipart-data in the Browser (Web API )?

FormData is a web api object that represent the data of a form that should be send if the form is submited. Therefore if you have a checkbox that is not checked, formdata will not collect it. You can...
Html Input File Multiple Warning Dialog
How to work with an Input File in an HTML form?

The input file is an input of type file that permits to select files or directory and send them to the browser file system api HTML HTML The HTML Result from the operating system: This...
Javascript - Map Data Type

in Javascript Object as associative array. A map object has also been create to implement a more sophisticated map type. Example: values return an iterator ...



Share this page:
Follow us:
Task Runner