因为JavaScript中的每个循环都让我抓狂
我的问题很简单。 我正在尝试用AJAX请求(数据)后接收的另一个对象列表更新对象列表(localDatz)。 所以它包含两个循环。。但当我尝试更新两个对象时,只更新一个对象。有件事我真的不明白。 有什么帮助吗因为JavaScript中的每个循环都让我抓狂,javascript,jquery,Javascript,Jquery,我的问题很简单。 我正在尝试用AJAX请求(数据)后接收的另一个对象列表更新对象列表(localDatz)。 所以它包含两个循环。。但当我尝试更新两个对象时,只更新一个对象。有件事我真的不明白。 有什么帮助吗 // fetch the localdata first var localData = getAll(); // Loop through my 'localData' $.each(localData.features, function(index,
// 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);
}
});
});
您正在修改使用以下代码循环的列表:
if (feature.properties.id==newFeature.properties.id){
localData.features.splice(index,1);
localData.features.push(newFeature);
}
不仅要修改列表条目,还要修改顺序(推到列表的末尾),这会打乱.forEach
循环。简单地使用:
if (feature.properties.id==newFeature.properties.id){
localData.features[ index ] = newFeature;
}
根本不需要使用
.splice
。如果不依赖将newFeature
附加到数组末尾,是否可以将其简化为localData.features.splice(索引,1,newFeature)代码>?我试过你的方法,效果很好!非常感谢。但是这种方法和push方法之间到底有什么不同呢?正如下面freakish的回答所示,区别在于push
将元素附加到数组的末尾,而splice
在指定的索引处添加元素。但是,您可以直接使用freakish的答案覆盖项目,而无需使用splice
。出于兴趣,直接覆盖项目而不是使用splice
,是否有性能优势?我想是的,因为涉及的操作较少。你好,怪物,非常感谢你的解释。(Stackoverflow的响应能力给我留下了深刻的印象!)我不知道push方法会弄乱forEach迭代器。我尝试了你的代码,它解决了我的问题。再次感谢你的帮助。非常感谢。Gallien@ChrisFrancis实际上,只有一点性能优势。实际上,splice
执行更多的操作,但这些操作是在指针上完成的,因此它们非常快。