迭代JS中的数组 - 可以在console.log()上查看它,但$ .each()拒绝迭代它

时间:2012-01-23 17:08:21

标签: javascript jquery arrays loops

  

可能重复:
  Return value from ajax call?
  JavaScript asynchronous return value / assignment with jQuery

我有一个问题,我试图在JavaScript中迭代一个数组,但由于某种原因它没有这样做。我正在使用last.fm的API中的$ .get()回调构建数组并创建一个对象数组。然后,当我尝试迭代数组之后,它不起作用,长度为零。

我在这里发布了一个JSFiddle:

http://jsfiddle.net/MMps2/2/

有什么想法?我在这里有点生气!

注意:弹出你的JS控制台 - 我正在记录它的东西......

1 个答案:

答案 0 :(得分:3)

您的$.get请求以异步方式运行。你试图在结果有机会执行之前返回结果的值。相反,当get请求完成时,使用回调模式调用另一个函数。

编辑:示例:

// Fetch top artists for the passed in username
$.get('http://ws.audioscrobbler.com/2.0/', {method: 'user.getTopArtists', user: user, api_key: 'c2c920e0749f24f2661d54614335748d'}, function(data) {

    // No need to use your higher scope results variable anymore
    var results = [];

    $('artist', data).each(function(index, artist) {

        // For each artist in the result, build an object containing the artists name and MusicBrainz ID
            results.push({
                'name': $('name', artist).text(),
                'mbid': $('mbid', artist).text()
        });

    });

    // Here's where such a call would go
    sendResultsToWhateverObjectNeedsThem(results);

});