On the one hand, a lack of an equivalent to Python 3's range
is an annoyance in ES6. On the other hand, there are lots of workarounds. My question is why one workaround I tried actually works. To illustrate:
[...Array(10).keys()];
In case the reason I find this mysterious is not obvious, note that Array(10).keys()
is at least apparently empty.
I'm aware this wastefully creates two arrays, as do most of the popular workarounds, and, that (at the cost of creating a generator function) using a generator can avoid that. E.g.,
[...(function*(){let i = 0; while(i<10) yield i++;})()];
My question is only about why the first workaround produces the desired result.
Edit:
Judging from the answers, some people believe that the evaluation of Array(10)
is equivalent to the evaluation of Array.apply(null,Array(10))
. They are not. For example, .hasOwnProperty(0)
is false
for the former but true
for the latter. However, I am open to being persuaded they are the same in some way that matters here, since my understanding is clearly lacking at some key point. I suspect that the answer is that the result of iterating over the keys is determine by the length
property, which both share, rather than the actual array indexes that have been defined. If so, I would like to know that this behavior is normative.