2012-08-10 70 views
0

我的问题很简单。 我试图用一个AJAX请求(数据)后收到的另一个对象列表更新对象列表(localDatz)。 所以它包含两个循环..但是当我尝试更新两个对象时,只更新了一个对象。有一些我真的不明白。 有什么帮助吗?对于JavaScript中的每个循环都让我生气

// fetch the localdata first 
      var localData = getAll(); 

// Loop through my 'localData' 
$.each(localData.features, function(index,feature){ 

     // Loop through the new data that are received 
     $.each(data.features, function(){ 
      newFeature = this; 

      if (feature.properties.id==newFeature.properties.id){ 

      // i think here is the problem..but can't figure out how to fix it 
      // I remove the old feature and push the new one 
      localData.features.splice(index,1);                 
      localData.features.push(newFeature); 


      } 

    }); 

}); 
+0

如果你不是依赖'newFeature'被追加到数组的** end **,你能不能简化为'localData.features.splice(index,1,newFeature);'? – 2012-08-10 11:38:56

+0

我尝试了你的方法,它工作的很棒!谢谢 !但是这与推送方法之间真正的变化是什么? – gallab 2012-08-10 11:44:37

+0

差异,正如在怪异的回答下面,是'push'将元素追加到数组的末尾,而'splice'在指定的索引处添加。但是,您可以直接使用怪异的答案直接覆盖该项目,而无需使用“拼接”。 – 2012-08-10 11:47:13

回答

1

你modyfing你遍历这个代码列表:

if (feature.properties.id==newFeature.properties.id){ 
    localData.features.splice(index,1); 
    localData.features.push(newFeature); 
} 

不仅modyfing列表中的条目,但该命令,以及(你推到列表的末尾) ,这混淆了.forEach循环。使用简单:

if (feature.properties.id==newFeature.properties.id){ 
    localData.features[ index ] = newFeature; 
} 

根本没有必要使用.splice

+0

出于兴趣,直接覆盖项目而不是使用“拼接”会有性能好处吗?我想可能会有,因为涉及的操作较少。 – 2012-08-10 11:48:22

+0

你好奇怪,非常感谢你的解释。 (我对Stackoverflow的响应性印象深刻!)我不知道push方法可能会混淆forEach迭代器。我试过你的代码,它解决了我的问题。再次感谢你的帮助。非常感激。 Gallien – gallab 2012-08-10 11:49:02

+1

@ChrisFrancis其实只有轻微的性能优势。事实上,“拼接”可以做更多的操作,但是这些都是在指针上完成的,所以它们非常快。 – freakish 2012-08-10 11:51:45