Although there is no direct equivalent to Python 3's range
in ES6, there are several workarounds available. I am curious about the effectiveness of one specific workaround that actually works. Take this example:
[...Array(10).keys()];
The reason why this workaround functions as intended is somewhat mysterious because Array(10).keys()
seems empty at first glance.
I acknowledge that many common workarounds can be inefficient as they create unnecessary arrays. By utilizing a generator function, it is possible to avoid this issue without creating extra arrays. For instance:
[...(function*(){let i = 0; while(i<10) yield i++;})()];
The main focus of my question lies in understanding why the initial workaround yields the desired result.
Edit:
Based on responses, some suggest that evaluating Array(10)
is the same as evaluating Array.apply(null,Array(10))
, but they differ. For example, .hasOwnProperty(0)
returns
false</code for the former and <code>true
for the latter. I am willing to consider arguments that they are somehow equivalent in ways relevant to this context since my understanding is clearly lacking. It appears that iterating over keys is influenced by the shared length
property rather than defined array indexes. If this behavior is standard, I would like clarification on that aspect.