0

我的问题很简单。我正在尝试使用在 AJAX 请求(数据)之后收到的另一个对象列表来更新对象列表(localDatz)。所以它包含两个循环。但是当我尝试更新两个对象时,只有一个对象被更新。有一点我真的不明白。有什么帮助吗?

    // 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);


            }

    });

});
4

1 回答 1

1

您正在修改您使用此代码循环的列表:

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

于 2012-08-10T11:42:49.193 回答