In PHP, you can do...
range(1, 3); // Array(1, 2, 3)
range("A", "C"); // Array("A", "B", "C")
That is, there is a function that lets you get a range of numbers or characters by passing the upper and lower bounds.
Is there anything built-in to JavaScript natively for this? If not, how would I implement it?
Using Harmony spread operator and arrow functions:
Example:
There's an npm module bereich for that ("bereich" is the German word for "range"). It makes use of modern JavaScript's iterators, so you can use it in various ways, such as:
It also supports descending ranges (by simply exchanging
min
andmax
), and it also supports steps other than1
.Disclaimer: I am the author of this module, so please take my answer with a grain of salt.
The standard Javascript doesn't have a built-in function to generate ranges. Several javascript frameworks add support for such features, or as others have pointed out you can always roll your own.
If you'd like to double-check, the definitive resource is the ECMA-262 Standard.
d3 also has a built-in range function. See https://github.com/mbostock/d3/wiki/Arrays#d3_range:
Example:
A rather minimalistic implementation that heavily employs ES6 can be created as follows, drawing particular attention to the
Array.from()
static method:Here's a nice short way to do it in ES6 with numbers only (don't know its speed compares):
For a range of single characters, you can slightly modify it: