I am newbie with javascript and trying to play with API, I don't know why there are some lines of code don't execute after the for loop is done. Could anyone help me ?
function jsonFlickrApi(data) {
if (data.stat != 'ok') {
alert('no image loaded');
} else {
for (var i = 0; i <= data.photos.photo.length; i++) {
addImage(data.photos.photo[i].url_o);
var lat = data.photos.photo[i].latitude;
var lon = data.photos.photo[i].longitude;
var LatLon = {
lat: parseFloat(lat),
lng: parseFloat(lon)
};
var markers = new google.maps.Marker({
'position': LatLon,
'map': map,
});
console.log("i", i);
photoMarkers.push(markers);
//It still executes well here.
};
//After the loop is finished, it doesn't print out anything to the console.
console.log("here");
};
//The following line doesn't execute too
fitMap(photoMarkers);
}
That loop doesn't finish, it throws an exception. Open your web console to see the details, you'll find something like:
Uncaught TypeError: Cannot read property 'url_o' of undefined
Array indexes are 0
through length-1
, so you want your for
loop to be < data.photos.photo.length
, not <= data.photos.photo.length
. On the last iteration of your <=
loop, data.photos.photo[i]
is undefined
so trying to get the value of data.photos.photo[i].url_o
throws.