Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript create array from for loop

I have a years range stored into two variables. I want to create an array of the years in the range.

something like:

var yearStart = 2000; var yearEnd = 2040;  var arr = [];  for (var i = yearStart; i < yearEnd; i++) {       var obj = {         ...       };        arr.push(obj); } 

What should I put inside the obj ?

The array I'd like to generate would be like:

arr = [2000, 2001, 2003, ... 2039, 2040] 
like image 809
Mauro74 Avatar asked Sep 19 '12 08:09

Mauro74


People also ask

How do you create an array for loops in Java?

You can use ArrayList for creating an array of array, else go for a 2D String array. Show activity on this post. you might want to use a 2D array which might offers what you need. String [][] test = new String [10][10];

How can you create an array in JavaScript using array literal?

Creating an Array Using an array literal is the easiest way to create a JavaScript Array. Syntax: const array_name = [item1, item2, ...]; It is a common practice to declare arrays with the const keyword.

Can you make an array of objects in JavaScript?

Creating an array of objectsWe can represent it as an array this way: let cars = [ { "color": "purple", "type": "minivan", "registration": new Date('2017-01-03'), "capacity": 7 }, { "color": "red", "type": "station wagon", "registration": new Date('2018-03-03'), "capacity": 5 }, { ... }, ... ]


2 Answers

even shorter if you can lose the yearStart value:

var yearStart = 2000; var yearEnd = 2040;  var arr = [];  while(yearStart < yearEnd+1){   arr.push(yearStart++); } 

UPDATE: If you can use the ES6 syntax you can do it the way proposed here:

let yearStart = 2000; let yearEnd = 2040; let years = Array(yearEnd-yearStart+1)     .fill()     .map(() => yearStart++); 
like image 71
Mat Avatar answered Sep 27 '22 23:09

Mat


You need to push i

var yearStart = 2000; var yearEnd = 2040;  var arr = [];  for (var i = yearStart; i < yearEnd+1; i++) {     arr.push(i); } 

Then, your resulting array will be:

arr = [2000, 2001, 2003, ... 2039, 2040]

Hope this helps

like image 37
Littm Avatar answered Sep 27 '22 21:09

Littm