JS: Range Function for Array
There's no builtin range function to creat a array.
0 Index Based Range Function
The easiest way to create a array from 0 to n is:
[... Array(n).keys()]
Here's how it works:
Array(n)
[see Array Constructor]
creates a
Sparse Array
of n elements.
.keys()
[see Array.prototype.keys]
return its indexes, as a
iterable object.
The
Spread Operator
...
wrapped with square bracket makes it an actual array.
General Range Function
Here's a general range function.
/* [ xah_range(min, max) β return a array from min to max, inclusive. xah_range(min, max, step) β in steps of step. If step is not integer, then max may not be included. http://xahlee.info/js/javascript_range_array.html version 2019-10-31 ] */ const xah_range = (( min, max, step = 1, ) => (Array(Math.floor((max - min) / step) + 1).fill(min).map( ((x, i) => (x + i * step)), )));
back to Array How-To