0

我正在尝试在javascript中创建一个对象数组,但是当我尝试将数组打印到控制台(使用chrome)时,我得到的只是未定义,除非我在推送之后打印数组。

 var subitems = [];
 for (var i = 1; i < 1000; i = i + 50) {
       $.getJSON('http://gdata.youtube.com/feeds/api/users/' + username + '/subscriptions?max-results=50&start-index=' + i + '&alt=json', function (data) {
           var output = "";
           for (var x in data.feed.entry) {
               var subtitle = data.feed.entry[x].yt$username.$t;
               var subchannel = data.feed.entry[x].yt$channelId.$t;
               var subphoto = data.feed.entry[x].media$thumbnail.url;
               subitems.push({
                   subtitle: subtitle,
                   subchannel: subchannel,
                   subphoto: subphoto
               });
               console.log(subitems[0]); //Prints Fine
               output += '<div class="subtitle"><img src="' + subphoto + '"> <a href="http://www.youtube.com/channel/' + subchannel + '">' + propercase(subtitle) + '</a></div>';
           }
           maincontent.innerHTML = maincontent.innerHTML + output;
       });
 }
 console.log(subitems[0]); //This is undefined
4

2 回答 2

1

这是执行此操作的“更简单”的方法:计数 XHR 请求并在所有请求都返回时触发 done 函数:

var xhrCount = 0;
for (var i = 1; i < 1000; i = i + 50) {
    xhrCount++; // increment before request
    $.getJSON('http://gdata.youtube.com/feeds/api/users/' + username + '/subscriptions?max-results=50&start-index=' + i + '&alt=json', function (data) {
            // process response      
            // decrement after request is processed
            xhrCount--;
            if (xhrCount === 0) {
                // at this point all requests have returned  
                console.log(subitems);
            }
        }
    }
}

更新:更好的方法是利用jQuery.Deferred()object. 此处设置了一个快速演示,需要一些修复。总体思路是跟踪您发出的所有 AJAX 请求,将它们传递给deferred.when()并使用deferred.done(). 代码(为便于阅读而删减):

var subitems = [];
var deferreds = [];
for (var i = 1; i < 1000; i = i + 50) {
    var deferred = $.getJSON('https://gdata.youtube.com/feeds/api/users/warnerbrospictures/uploads?max-results=50&start-index=' + i + '&alt=json', function (data) {
        for (var j = 0; j < data.feed.entry.length; j++) {
            subitems.push({
                title: data.feed.entry[j].title.$t
            });
        }
    });
    deferreds.push(deferred);
}
$.when.apply($, deferreds).done(function () {
    console.clear();
    console.log(subitems);
    for (var i = 0; i < subitems.length; i++) {
        console.log(subitems[i].title);
    }
});

注意:Google 数据提要包含结果总数,因此可以消除硬编码的“1000”。

于 2013-08-17T09:56:33.487 回答
-2

尝试将您的数组声明为:

var subitems = [{}];
于 2013-08-17T09:46:41.020 回答