Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
73
rated 0 times [  77] [ 4]  / answers: 1 / hits: 34056  / 11 Years ago, sat, october 12, 2013, 12:00:00

I'm brand new to javascript. I was working through a problem earlier where I needed an array that included the numbers 1 thru 20.



I did this with the following:



var numberArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];


QUESTION:



I can't help but think that this is not efficient (and certainly not scalable). Is there a way to create an array that automatically populates with sequential values between 1 and 20, or 1 and 1000 for instance?


More From » arrays

 Answers
81

You could use a simple loop to do what you want;



var numberArray = [];

for(var i = 1; i <= 20; i++){
numberArray.push(i);
}

console.log(numberArray);

[#75034] Friday, October 11, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
alysas

Total Points: 616
Total Questions: 111
Total Answers: 124

Location: Slovenia
Member since Wed, Apr 6, 2022
2 Years ago
alysas questions
Sun, Jul 19, 20, 00:00, 4 Years ago
Tue, Jun 23, 20, 00:00, 4 Years ago
Mon, Mar 30, 20, 00:00, 4 Years ago
;