for-of statement of sparse array

Jason Orendorff jason.orendorff at gmail.com
Thu Jul 5 09:54:02 PDT 2012


On Thu, Jul 5, 2012 at 6:11 AM, teramako <teramako at gmail.com> wrote:
> Firefox 15 or later can use for-of statement.
> I have a question about this.
>
>     var array = new Array(3);
>     for (var i in array) {
>       console.log(i);
>     }
>     for (var v of array){
>       console.log(v);
>     }
>
> This for-in code logs nothing of course but for-of code logs 3 of undefined.
[...]
> Are these behaviors correct ?

Well, they're certainly intentional. There's no final specification
yet, so it could change.

The rationale for this is that for-of should act like the canonical
for-loop over an array:

    var array = new Array(3);
    for (var i = 0; i < array.length; i++)
        console.log(array[i]);  // "undefined" 3 times

    for (var v of array)
        console.log(v);  // "undefined" 3 times

The corresponding for-in loop is much rarer, with good reason. Note
that "for-in" on an Array is underspecified (in terms of the order in
which the property names are visited and what happens when properties
are added or removed during iteration). The behavior we implemented
for Array iterators is straightforward and easy to use, and it's
easier to specify fully. See
<http://wiki.ecmascript.org/doku.php?id=harmony:iterators>.

I think Map will end up being better than Array for sparse collections.

-j


More information about the es-discuss mailing list