猿问

for循环中 动态创建的变量怎么动态的赋值呢?

  for(var i=0;i<mydata.length;i++){

                               var field = "field" + i;//field0、 field1、 field2 、field3

                              field=mydata[i].CREW_NAME;//1号机组、2号机组 、3号机组 、4号机组

                              console.log(field);

                                    }

我怎么让 field0 等于1号机组 以此类推呢?

// console.log(field0);

// console.log(field1);

// console.log(field1);

// console.log(field1);


30秒到达战场
浏览 957回答 2
2回答

喵喵时光机

for(var i=0;i<mydata.length;i++){&nbsp; &nbsp;var field = "field" + i;&nbsp; &nbsp;window[field] = mydata[i].CREW_NAME;//1号机组、2号机组 、3号机组 、4号机组}console.log(window.field0);console.log(window.field1);使用普通对象存储var fields = {};for(var i=0;i<mydata.length;i++){&nbsp; &nbsp;var field = "field" + i;&nbsp; &nbsp;fields[field] = mydata[i].CREW_NAME;//1号机组、2号机组 、3号机组 、4号机组}console.log(fields.field0);console.log(fields.field1);

海绵宝宝撒

&nbsp; var mydata =[&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; CREW_NAME:'1号机组',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; CREW_NAME:'2号机组',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; CREW_NAME:'3号机组',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; CREW_NAME:'4号机组',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; ];&nbsp; &nbsp; &nbsp; &nbsp; var field=[];&nbsp; &nbsp; &nbsp; &nbsp; mydata.forEach( (item)=> {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; field.push(item.CREW_NAME)&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; console.log(field[0]);&nbsp; &nbsp; &nbsp; &nbsp; console.log(field[1]);&nbsp; &nbsp; &nbsp; &nbsp; console.log(field[2]);&nbsp; &nbsp; &nbsp; &nbsp; console.log(field[3]);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答