我有以下代码用于使用JSON对象填充全局数组
// global arrays declaration
var sectionL=[1,5,3,7,5,4,3,3,4,4,6,6,3,5,5,1];
var sectionsTitle=new Array(16);
var sectionsContent=new Array(16);
for(var i=0; i<sectionL.length;i++){
sectionsTitle[i]=new Array(sectionL[i]);
sectionsContent[i]=new Array(sectionL[i]);
}
var country = new Array(4);
for(var i=0;i<5;i++){
country[i]=new Array();
country[i][2]=sectionsTitle;// allocate see above
country[i][3]=sectionsContent;// allocate see above
//////////////////////////////////////
function getCountries(data){
$.each(data['countries'], function (k,val){
country[k][0]=val['title']; // store the title
country[k][1]=val['id']; // store the id to send to the JSON
$.getJSON(baseURL+country[k][1]+'&callback=?',function(data ){
console.log("k=>"+k+" id=>"+country[k][1]); // just to check if k is passed
for(var i=0;i<1;i++){
index=i+1;
for(var j=0;j<1;j++){
country[k][2][i][j]=data['result']['sectionTitles']['section'+index+'.'+j+'.title']; // fill the array with the content
}
}
});
});
console.log(country);
返回
[Array[4], Array[4], Array[4], Array[4], Array[4]]
k=>0 id=>9
k=>1 id=>29
k=>3 id=>31
k=>4 id=>12
k=>2 id=>7
问题:数组的值被覆盖,只显示最后一个。 我怀疑是关闭问题,但我被困住了。任何提示将不胜感激!
答案 0 :(得分:0)
最后,我认为问题在于
country[i][2]=sectionsTitle;// allocate see above
country[i][3]=sectionsContent;// allocate see above
你要为所有东西分配相同的对象,所以所有都引用同一个对象,因此问题,一个解决方案可能是......
...
country[i][2]=getSectionDetails(sectionL);// allocate see above
country[i][3]=getSectionDetails(sectionL);// allocate see above
...
function getSectionDetails(data){
var details=[]
data.forEach(function(v){ details.push([v]);});
return details;
}
<强>上强>:
<击>
我假设问题是$.getJSON
与其他人共享变量k
,我的解决方案是......
function getCountries(data){
var url;
$.each(data['countries'], function (k,val){
country[k][0]=val['title']; // store the title
country[k][1]=val['id']; // store the id to send to the JSON
url = baseURL+country[k][1]+'&callback=?';
$.getJSON(url, onJSONData.bind({k:k, url: url}));
});
}
function onJSONData(data){
var k = this.k;
console.log("k=>",k," url=>",this.url, 'data =>', data); // just to check if k is passed
country[k][2][0][0]=data.result.sectionTitles.section1[0].title; // fill the array with the content
}