最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Add values to array using for loop in JavaScript - Stack Overflow

programmeradmin0浏览0评论

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.

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.

Share Improve this question edited Dec 8, 2020 at 14:14 General Grievance 4,98838 gold badges37 silver badges55 bronze badges asked Sep 3, 2013 at 6:23 neelneel 5,29312 gold badges49 silver badges67 bronze badges 3
  • did you search anything about it ? – Deepanshu Goyal Commented Sep 3, 2013 at 6:27
  • 3 He has tried something. It did not work. So i think its a valid question – MarsOne Commented Sep 3, 2013 at 6:28
  • 1 to be fair, this is a valid line of python: arr = [{ "val": i, "text": i } for i in range(32)] and would produce the same result as above – Sanketh Katta Commented Sep 3, 2013 at 6:38
Add a comment  | 

1 Answer 1

Reset to default 16

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)

  1. 暂无评论