What's the most efficient way to create this simple array dynamically.
var arr = [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
Let's say we can get the number 10 from a variable
var mynumber = 10;
What's the most efficient way to create this simple array dynamically.
var arr = [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
Let's say we can get the number 10 from a variable
var mynumber = 10;
Sounds like you just want to construct an array that contains the string versions of the integer values. A simple approach:
For a more interesting version you could do a generator...
If you are asking whether there is a built in Pythonic
range
-like function, there isn't. You have to do it the brute force way. Maybe rangy would be of interest to you.The same way you would for all arrays you want to fill dynamically. A for loop. Suedo code is
that should help you on the way
I had a similar problem and a solution I found (forgot where I found it) is this:
Array.from(Array(mynumber), (val, index) => index + 1)
With ES2015, this can be achieved concisely in a single expression using the
Array.from
method like so:The first argument to
from
is an array like object that provides a length property. The second argument is a map function that allows us to replace the defaultundefined
values with their adjusted index values as you requested. Checkout the specification hereThis answer is about "how to dynamically create an array without loop".
Literal operator
[]
doesn't allow us to create dynamically, so let's look intoArray
, it's constructor and it's methods.In ES2015 Array has method
.from()
, which easily allows us to create dynamic Array:When Array's constructor receives number as first parameter, it creates an Array with size of that number, but it is not iterable, so we cannot use
.map()
,.filter()
etc. :But if we'll pass more than one parameter we will receive array from all parameters:
If we would use ES2015 we can use spread operator which will spread empty Array inside another Array, so we will get iterable Array :
But if we don't use ES2015 and don't have polyfills, there is also a way to create dynamic Array without loop in ES5. If we'll think about
.apply()
method: it spreads second argument array to params. So calling apply on Array's constructor will do the thing:After we have dynamic iterable Array, we can use map to assign dynamic values: