MENU
Overriding Built in Iterables
Below, a closure is used to pass the value of i to the iterator.
RESETRUNFULL
<!DOCTYPE html><html><body><script>
var s = new String('hello'); // = “hello" will allow auto-boxings[Symbol.iterator] = function(){ // always, [Symbol.iterator]() takes 0 argument
return { // the method must return an iterator
next: function() { // again, next() takes 0 argument
if (this.i<2) {
this.i++;
return { value: "abc"[this.i], done: false };
} else {
return { done: true };
}
},
i: -1
};}for (v of s) console.log(v); // a b cconsole.log([...s]); // ["a","b","c"]
</script></body><html>