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]
This question is related to
javascript
arrays
for-loop
var yearStart = 2000;
var yearEnd = 2040;
var arr = [];
for (var i = yearStart; i <= yearEnd; i++) {
arr.push(i);
}
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
Remove obj
and just do this inside your for loop:
arr.push(i);
Also, the i < yearEnd
condition will not include the final year, so change it to i <= yearEnd
.
Source: Stackoverflow.com