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]
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];
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.
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 }, { ... }, ... ]
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++);
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
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