$.each statement stops when it gets to “undefined” value-Collection of common programming errors
I’m pretty sure the reason you’re getting an undefined value during iteration when your starting array doesn’t have any undefined values in it is that you’re removing items from the array while iterating through it. I guess this confuses the jQuery $.each()
iterator.
If you look at your output, what is happening is this:
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.
Notice that two of the items never got evaluated: the iterator skipped over them because you changed their indexes by removing items.
If you must remove items as you go it is easy with a conventional for loop that iterates backwards such that removing items won’t screw up the loop counter. (Or you can use a conventional for loop to go forwards as long as you adjust the counter variable each time you remove an item.)
Also, when you do splice you need to pass the index of the item as the first parameter, not the value of the item. So markersArray.splice(index, 1);
not markersArray.splice(value, 1);
.
So, something like:
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");
}
}
}
Originally posted 2013-11-09 21:10:36.