Author Topic: ES6 For-Of loop  (Read 917 times)

Offline Flying Jester

  • TurboSphere Developer
  • Verified
  • Legendary Poster
  • *
  • Posts: 1152
    • View Profile
ES6 For-Of loop
« 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

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 »

Online Fat Cerberus

  • miniSphere Developer
  • Verified
  • Legendary Poster
  • *
  • Posts: 2166
  • *MUNCH*
    • View Profile
Re: ES6 For-Of loop
« Reply #1 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.
miniSphere 4.5.11 - Cell compiler - SSJ debugger
Forum Thread | GitHub Repo

Offline DaVince

  • Who's an oracle? Not me!
  • Senior Staff
  • Hero Poster
  • *****
  • Posts: 745
    • View Profile
    • Vincent Beers portfolio
Re: ES6 For-Of loop
« Reply #2 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.

Online Fat Cerberus

  • miniSphere Developer
  • Verified
  • Legendary Poster
  • *
  • Posts: 2166
  • *MUNCH*
    • View Profile
Re: ES6 For-Of loop
« Reply #3 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
  1. let obj = {
  2.     *[Symbol.iterator]() {
  3.         for (let i = 0; i < 3; ++i)
  4.             yield i;
  5.     }
  6. };
  7. for (let n of obj)
  8.     console.log(n);
  9.  

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.
miniSphere 4.5.11 - Cell compiler - SSJ debugger
Forum Thread | GitHub Repo

 

anything