Re: ES6 For-Of loop
Reply #3 –
Now that ES6 is out and I've had time to actually play with it, it turns out you can override for-of behavior for any object (of course you probably know this already by now
) - by assigning a generator function to obj[Symbol.iterator]. The generator should yield all the values that for...of must iterate over. For example:
let obj = {
*[Symbol.iterator]() {
for (let i = 0; i < 3; ++i)
yield i;
}
};
for (let n of obj)
console.log(n);
1
2
3
The indirection with [Symbol.iterator] is kind of weird, but overall the methodology isn't too different from a .toString() override.