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]
-
I posted an answer which gives both highest number as well as all values if highest number is greater then your certain numbershivgre– shivgre2016年04月05日 10:47:41 +00:00Commented Apr 5, 2016 at 10:47
5 Answers 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++);
Comments
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
Comments
var yearStart = 2000;
var yearEnd = 2040;
var arr = [];
for (var i = yearStart; i <= yearEnd; i++) {
arr.push(i);
}
Comments
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.
Comments
If you like generators, then this might be a more elegant approach:
function* range(start, stop) {
for (let i = start; i < stop; i++) yield i;
}
const years = range(2000, 2040).toArray();
console.log(years);