Is it possible to define an array iterator that adjusts to your for-of syntax?

Jason Orendorff jason.orendorff at gmail.com
Mon May 23 14:47:43 UTC 2016


No, it's not possible.

Oddly enough, when this functionality was first prototyped in
SpiderMonkey many years ago, the iterator protocol *did* pass a
boolean to the __iterator__ method (this was before symbols) based on
the syntax you were using to unpack the results. This feature was not
super useful in practice, and I always thought it was too subtle --
the difference in syntax was really not explicit enough to make it
clear to the programmer what was going on. I'm glad it wasn't
standardized.

-j


On Sun, May 22, 2016 at 12:55 PM, Šime Vidas <sime.vidas at gmail.com> wrote:
> Say I have an array over which I need to iterate multiple times, but I need
> the index value only some of the time. Is it possible to create a custom
> iterator which auto-detects when I need the index and feeds me entries()
> instead of values() in those cases? For example:
>
> array[Symbol.iterator] = /* some magic here */
>
> for (let elem of array) { /* values() iterator is used automatically */ }
> for (let [i, elem] of array) { /* entries() iterator is used automatically
> */ }
>
>
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>


More information about the es-discuss mailing list