我的问题很简单。 我试图用一个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);
}
});
});
如果你不是依赖'newFeature'被追加到数组的** end **,你能不能简化为'localData.features.splice(index,1,newFeature);'? – 2012-08-10 11:38:56
我尝试了你的方法,它工作的很棒!谢谢 !但是这与推送方法之间真正的变化是什么? – gallab 2012-08-10 11:44:37
差异,正如在怪异的回答下面,是'push'将元素追加到数组的末尾,而'splice'在指定的索引处添加。但是,您可以直接使用怪异的答案直接覆盖该项目,而无需使用“拼接”。 – 2012-08-10 11:47:13