[javascript] 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]

This question is related to javascript arrays for-loop

The answer is


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.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to for-loop

List append() in for loop Prime numbers between 1 to 100 in C Programming Language Get current index from foreach loop how to loop through each row of dataFrame in pyspark TypeScript for ... of with index / key? Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply? Python for and if on one line R for loop skip to next iteration ifelse How to append rows in a pandas dataframe in a for loop? What is the difference between ( for... in ) and ( for... of ) statements?