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);
})