Javascript对象数组未定义

时间:2013-08-17 09:43:43

标签: javascript jquery arrays ajax object

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

 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

2 个答案:

答案 0 :(得分: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()对象。一个quick demo is setup here,需要一些修复。一般的想法是跟踪您所做的所有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数据Feed包含结果总数,因此可以消除硬编码“1000”。

答案 1 :(得分:-2)

尝试将数组声明为:

var subitems = [{}];