$ .each语句在达到“未定义”值时停止

时间:2011-12-31 03:13:35

标签: javascript jquery google-maps google-maps-api-3 google-maps-markers

使用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"]

显然,数组成功运行,直到达到“未定义”值,然后停止。我该怎么做才能解决这个问题?

3 个答案:

答案 0 :(得分:3)

我很确定你在启动数组中没有任何未定义值时在迭代期间获得未定义值的原因是你在迭代它时从数组中删除项目。我想这会混淆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");
      }
   }
}

答案 1 :(得分:2)

我认为dotnetstep会对它进行修改,但您也可以尝试使用try / catch包装$.each内的逻辑以进行更广泛的处理:

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

祝你好运!

答案 2 :(得分:1)

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