0

私の問題はかなり単純です。オブジェクトのリスト (localDatz) を、AJAX 要求 (データ) の後に受け取った別のオブジェクトのリストで更新しようとしています。したがって、2つのループで構成されています..しかし、2つのオブジェクトを更新しようとすると、1つのオブジェクトのみが更新されます。どうしてもわからないことがあります。助けはありますか?

    // 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 に答える