Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
76
rated 0 times [  78] [ 2]  / answers: 1 / hits: 23096  / 9 Years ago, mon, january 25, 2016, 12:00:00

Let's say I want a variable to contain numbers from 1 to 100.
I could do it like this:



var numbers = [1,2,3,4,...,98,99,100]


But it would take a bunch of time to write all those numbers down.
Is there any way to set a range to that variable? Something like:



var numbers = [from 1, to 100] 


This might sound like a really nooby question but haven't been able to figure it out myself. Thanks in advance.


More From » variables

 Answers
7

In addition to this answer, here are some ways to do it:



for loop:



var numbers = []
for (var i = 1; i <= 100; i++) {
numbers.push(i)
}




Array.prototype.fill + Array.prototype.map



var numbers = Array(100).fill().map(function(v, i) { return i + 1; })


Or, if you are allowed to use arrow functions:



var numbers = Array(100).fill().map((v, i) => i + 1)


Or, if you are allowed to use the spread operator:



var numbers = [...Array(100)].map((v, i) => i + 1)




However, note that using the for loop is the fastest.


[#63563] Saturday, January 23, 2016, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
viridianaw

Total Points: 154
Total Questions: 94
Total Answers: 89

Location: South Georgia
Member since Sun, Aug 8, 2021
3 Years ago
;