I'm looking for any alternatives to the below for creating a JavaScript array containing 1 through to N where N is only known at runtime.
var foo = []; for (var i = 1; i <= N; i++) { foo.push(i); }
To me it feels like there should be a way of doing this without the loop.
Use the range() Function to Create a List of Numbers From 1 to N. The range() function is very commonly used in Python. It returns a sequence between two numbers given in the function arguments. The starting number is 0 by default if not specified.
To create an array of values, you simply add square brackets following the type of the values that will be stored in the array: number[] is the type for a number array. Square brackets are also used to set and get values in an array.
Elements in an array are obtained by using a zero-based index. That means the first element is at index 0, the second at index 1, and so on. Therefore, if the array has size N , the last element will be at index N-1 (because it starts with 0 ). Thus the index is in the interval [0, N-1] .
In ES6 using Array from()
and keys()
methods.
Array.from(Array(10).keys()) //=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Shorter version using spread operator.
[...Array(10).keys()] //=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Start from 1 by passing map function to Array from()
, with an object with a length
property:
Array.from({length: 10}, (_, i) => i + 1) //=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With