简体   繁体   中英

Dynamic variable in javascript push function

I'm using push function in javascript.

var chartData = [];
for(var i=0; i<3; i++) {

    chartData.push({

        date: new Date(year_s,mon_s,date_s,hr_s,min_s,sec_s),
        visits: chartData1[selection[i]][j].value,
        customBullet: show_annotations,
        balloonTextField: "testtesttest"
    });

}

I need to pass a dynamic variable like visits_1, visits_2, etc,. in place of visits variable in the above code. I have tried visits+"_"+i. But it is not working. Please help me to achieve this. Thanks in advance.

You have to make it in two steps :

var chartData = [];
for(var i=0; i<3; i++) {
   // 1. create the object
   var d =  { 
      date: new Date(year_s,mon_s,date_s,hr_s,min_s,sec_s),
      customBullet: show_annotations,
      balloonTextField: "testtesttest"
   };
   // 2. then assign the visits_i property
   d['visits_'+i] = chartData1[selection[i]][j].value; 
   chartData.push(d);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM