https://hacks.mozilla.org/2015/04/es6-in-depth-iterators-and-the-for-of-loop/?utm_source=Newsletter&utm_medium=email&utm_campaign=DevProgram (https://hacks.mozilla.org/2015/04/es6-in-depth-iterators-and-the-for-of-loop/?utm_source=Newsletter&utm_medium=email&utm_campaign=DevProgram)
This looks very cool. It's kind of what for-in seems like, but instead of actually iterating properties it only iterates using the data itself.
Seeing this (especially with destructuring), though, it makes me wish that there was a way for an object to expressly rewrite the data operator, sort of how toString() can be used.
I remember reading about for-of a while ago, but I didn't know about the destructuring. That's awesome.
This, combined with the Map object they explained, look like super useful additions. the whole (var i = 0; i < blah; i++) deal always felt clunky and overused to me, especially when you don't really need to know the value of i.
Seeing this (especially with destructuring), though, it makes me wish that there was a way for an object to expressly rewrite the data operator, sort of how toString() can be used.
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.