I have this code inside the success function of a jQuery ajax call success: function(d)
for (var n in d.items)
{
google.maps.event.addListener(markers[d.items[n].id], 'mouseover', function() {
focusMarker(d.items[n].id);
});
}
Unfortunately, the function always evaluated d.items[n].id as the last item in d.items collection.
I tried making this modification:
for (var n in d.items)
{
var id = d.items[n].id;
google.maps.event.addListener(markers[d.items[n].id], 'mouseover', function() {
focusMarker(id);
});
}
but my function always returned the same thing.
Is this a scope problem, or is there something wrong with my function definition?
There are several ways to solve this problem, the most common is to use a function to preserve the looping values:
By the way, if
d.itemsis an array, I would recommend you to use a sequential loop e.g.:The
for-instatement is meant to be used to enumerate over object properties.If you use it on arrays or array like objects, it can give you several problems, first, inherited properties are also enumerated, meaning that if someone augments the
Array.prototypeobject, those properties will be also enumerated in your loop.Also the order of iteration is not guaranteed by the specification, the properties may not be visited in the numeric order.