Spherical forums

General Discussion => Off-Topic Discussions => Topic started by: Flying Jester on May 05, 2015, 04:01:50 pm

Title: ES6 For-Of loop
Post by: Flying Jester on May 05, 2015, 04:01:50 pm
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.
Title: Re: ES6 For-Of loop
Post by: Fat Cerberus on May 05, 2015, 04:08:19 pm
I remember reading about for-of a while ago, but I didn't know about the destructuring.  That's awesome.
Title: Re: ES6 For-Of loop
Post by: DaVince on May 06, 2015, 09:38:43 am
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.
Title: Re: ES6 For-Of loop
Post by: Fat Cerberus on March 10, 2017, 11:51:11 pm

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:

Code: (javascript) [Select]

let obj = {
    *[Symbol.iterator]() {
        for (let i = 0; i < 3; ++i)
            yield i;
    }
};
for (let n of obj)
    console.log(n);


Code: [Select]

1
2
3


The indirection with [Symbol.iterator] is kind of weird, but overall the methodology isn't too different from a .toString() override.