Add Values to Array Using for Loop in Javascript

Add Values to Array Using for Loop in Javascript

I know this is a simple issue, but I am stumped.

I want to do this using a for loop in JavaScript

      var arr = [
        { val: '1', text: '1' },
        { val: '2', text: '2' },
        { val: '3', text: '3' },
       .........
        { val: '30', text: '30' },
        { val: '31', text: '31' }
       ];

I tried this. I want create a select list which shows all month day

    var arr = [
        for (var i = 0; i < 32; i++) {
             { val: i, text: i },
        }
    ];

This shows error.

3

1 Answer

Javascript does not have list comprehensions like that, try this instead:

var arr = [];
for (var i = 0; i < 32; i++) {
    arr.push({ val: i, text: i });        
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Robert Thorne
Author

Robert Thorne

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.