Skip to main content

News

Topic: ES6 For-Of loop (Read 5046 times) previous topic - next topic

0 Members and 2 Guests are viewing this topic.
ES6 For-Of loop
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.
  • Last Edit: May 05, 2015, 04:03:50 pm by Flying Jester

  • Fat Cerberus
  • [*][*][*][*][*]
  • Global Moderator
  • Sphere Developer
Re: ES6 For-Of loop
Reply #1
I remember reading about for-of a while ago, but I didn't know about the destructuring.  That's awesome.
neoSphere 5.9.2 - neoSphere engine - Cell compiler - SSj debugger
forum thread | on GitHub

  • DaVince
  • [*][*][*][*][*]
  • Administrator
  • Used Sphere for, like, half my life
Re: ES6 For-Of loop
Reply #2
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.

  • Fat Cerberus
  • [*][*][*][*][*]
  • Global Moderator
  • Sphere Developer
Re: ES6 For-Of loop
Reply #3

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.
neoSphere 5.9.2 - neoSphere engine - Cell compiler - SSj debugger
forum thread | on GitHub