簡體   English   中英

$ .each語句在達到“未定義”值時停止

[英]$.each statement stops when it gets to “undefined” value

使用Google Maps V3標記時,請確保將每個標記的名稱存儲在一個數組中,以便快速將所有標記立即從地圖上刪除。 但是由於某種原因,當我調用應該遍歷整個數組的函數時,很長一段時間都刪除了所有標記,該函數僅刪除了一些標記后返回undefined。

函數之前的數組(markersArray):

["markerZip02111", "markerZip02139", "markerZip01002", "markerZip94602", "markerZip02460"]

功能代碼:

function removeAllMarkers(exceptId) {
    $.each(markersArray, function(index, value) {
        if(value != exceptId) {
            eval(value+".setMap(null);");
            markersArray.splice(value, 1);
            console.log(value);
        }
    });
}

控制台顯示的內容:

markerZip02111
markerZip01002
markerZip02460
undefined

函數運行后的數組:

["markerZip94602", "markerZip02460"]

顯然,數組成功運行直到它達到“ undefined”值,然后停止。 我該怎么辦才能解決這個問題?

我很確定,在起始數組中沒有任何未定義值的情況下,在迭代過程中獲得未定義值的原因是,您要在遍歷數組時從數組中刪除項目。 我猜想這會混淆jQuery $.each()迭代器。

如果查看您的輸出,將會發生以下情況:

1st Iteration
    index === 0, array is["markerZip02111", "markerZip02139", "markerZip01002",
                          "markerZip94602", "markerZip02460"]
    item 0 "markerZip02111" gets removed, shifting all the later elements up
2nd Iteration
    index === 1, but now array is ["markerZip02139", "markerZip01002",
                                   "markerZip94602", "markerZip02460"]
    item 1 "markerZip01002" gets removed, shifting all the later elements up
3rd Iteration
    index ===2, but now array is ["markerZip01002", "markerZip94602",
                                  "markerZip02460"]
    so the last item "markerZip02460" gets removed
4th Iteration
    index === 3, but now array only has two elements so value
    at that index is undefined.

請注意,其中兩個項目從未得到評估:迭代器跳過了它們,因為您通過刪除項目來更改了它們的索引。

如果您必須隨身攜帶物品,可以使用傳統的for循環輕松進行,該循環可以向后迭代,這樣移除物品就不會弄亂循環計數器。 (或者,只要您每次刪除項目時都調整計數器變量,就可以使用常規的for循環前進。)

同樣,在進行拼接時,需要將項目的索引作為第一個參數而不是項目的值傳遞。 因此markersArray.splice(index, 1); 不是 markersArray.splice(value, 1);

因此,類似:

function removeAllMarkers(exceptId) {
   var value;
   for (var i = markersArray.length - 1; i >= 0; i--) {
      value = markersArray[i];
      if (value != exceptId) {
         markersArray.splice(i, 1);
         eval(value+".setMap(null);");
         console.log(value + " removed");
      }
   }
}

我認為dotnetstep已將其釘牢,但您也可以嘗試使用$.each try / catch將$.each的邏輯包裝$.each ,以進行更廣泛的處理:

http://www.w3schools.com/js/js_try_catch.asp

祝好運!

   $.each(markersArray, function (index, value) {            
             if (value != null && value != undefined  && value!= exceptId) {
                 eval(value + ".setMap(null);");
                 markersArray.splice(value, 1);
                 console.log(value);
             }
         });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM