为什么某行代码在循环后不执行?

Why do some line of code doesn't execute after a loop?

我是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);

}

那个循环没有完成,它抛出了一个异常。打开您的 Web 控制台查看详细信息,您会发现类似以下内容:

Uncaught TypeError: Cannot read property 'url_o' of undefined

数组索引是 0length-1,因此您希望 for 循环是 < data.photos.photo.length,而不是 <= data.photos.photo.length。在你的 <= 循环的最后一次迭代中,data.photos.photo[i]undefined 所以试图获得 data.photos.photo[i].url_o 的值抛出。