我是javascript的新手,并尝试使用API,我不知道为什么在for循环完成后有一些代码行不会执行。有谁可以帮助我?
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);
}
答案 0 :(得分:3)
该循环未完成,它抛出异常。打开您的Web控制台以查看详细信息,您将找到类似的内容:
Uncaught TypeError: Cannot read property 'url_o' of undefined
数组索引为0
到length-1
,因此您希望for
循环为< data.photos.photo.length
,而不是<= data.photos.photo.length
。在<=
循环的最后一次迭代中,data.photos.photo[i]
为undefined
,因此尝试获取data.photos.photo[i].url_o
的值。