Javascript 数组推入 for 循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18988634/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript array push in a for loop
提问by Claude
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. Returning the array to the console in the second for loop
outputs the following:
我for loops
在第二个上有两个,我正在使用push
一个称为数组的数组myArray
,它没有推送所需的数据。在第二个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. The problem is that the arrays each have two elements which is why I am trying to push
it into one array.
注意:它出现这样的原因是因为我正在遍历一个 JSON 文件,该文件检查第一个中心并检索数组中的数据,然后转到下一个并执行相同的操作。问题是每个数组都有两个元素,这就是我尝试将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);
}
}
}
}
回答by Dipak Ingole
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);
}
}
});