[英]Javascript array push in a for loop
I have two for loops
on the second one I am using push
to an array called myArray
and it is not pushing the data has desired. 我在第二个上有两个
for loops
我正在使用push
到一个名为myArray
的数组,并且它没有推送所需的数据。 Returning the array to the console in the second for loop
outputs the following: 在第二个
for loop
中将数组返回到控制台输出以下内容:
["Scottsdale CFS"]
["Scottsdale CFS", "Denver CFS"]
["Warren CFS"]
["Warren CFS", "Millford CFS"]
["Rockaway CFS"]
["Rockaway CFS", "Border CFS"]
However, I would like the data to show like this: 但是,我希望数据显示如下:
["Scottsdale CFS", "Denver CFS", "Warren CFS", "Millford CFS", "Rockaway CFS", "Border CFS"]
How can I accomplish this? 我怎么能做到这一点?
note: The reason it is showing up like that is because I am iterating through a JSON file which checks through the first center and retrieves the data in an array and then goes to the next and does the same. 注意:它出现的原因是因为我正在迭代一个JSON文件,该文件检查第一个中心并检索数组中的数据,然后转到下一个并执行相同的操作。 The problem is that the arrays each have two elements which is why I am trying to
push
it into one array. 问题是每个数组都有两个元素,这就是我试图
push
它push
入一个数组的原因。
var looper = function(sec0, vz, lOrR) {
var myArray = [];
for(var i=0;i<vz[0]['Areas'].length;i++){
var tText = Object.keys(vz[0]['Areas'][i]);
var root = vz[0]['Areas'][i][tText][0];
var dataName;
}
var myArray = [];
if(sec0 === "Centers") {
for(var j=0;j<root[sec0].length;j++){
var myString = root[sec0][j]["Label"];
myArray.push(myString);
charts.chart.renderTo = lOrR+myArray.indexOf(root[sec0][j]["Label"]);
charts.title.text = root[sec0][j]["Label"];
dataName = root[sec0][j]['Metrics'][5]['Rep Res. %'].slice(0,-1);
charts.series[0].name = dataName;
charts.series[0].data = [parseFloat(dataName)];
new Highcharts.Chart(charts);
}
}
}
}
The only reason is you are re declaring your array var myArray = [];
唯一的原因是你要重新声明你的数组
var myArray = [];
Try with following code, 尝试使用以下代码,
var looper = function(sec0, vz, lOrR) {
var myArray = [];
for(var i=0;i<vz[0]['Areas'].length;i++){
var tText = Object.keys(vz[0]['Areas'][i]);
var root = vz[0]['Areas'][i][tText][0];
var dataName;
}
if(sec0 === "Centers") {
for(var j=0;j<root[sec0].length;j++){
var myString = root[sec0][j]["Label"];
myArray.push(myString);
charts.chart.renderTo = lOrR+myArray.indexOf(root[sec0][j]["Label"]);
charts.title.text = root[sec0][j]["Label"];
dataName = root[sec0][j]['Metrics'][5]['Rep Res. %'].slice(0,-1);
charts.series[0].name = dataName;
charts.series[0].data = [parseFloat(dataName)];
new Highcharts.Chart(charts);
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.