簡體   English   中英

如何在javascript中使用for循環檢索多個JSON對象

[英]How to retrieve multiple JSON objects with a for loop in javascript

我一直在使用Last.fm API和JSON,我一直試圖在過去12個月內按月檢索用戶的頂級藝術家。 我嘗試設置一個for循環來完成每個月,然后拉出與該月相對應的相關JSON數據,但從我可以看出,似乎for循環運行得比JSON調用快得多。

我正在使用Felix Bruns的last.fm javascript API https://github.com/fxb/javascript-last.fm-api

我檢查了控制台,沒有記錄月份的值,除了12。我還得到一個未捕獲的參考錯誤“json ## ....未定義”

我試着尋找解決方案,但我的所有搜索結果都是如何循環API調用的結果,而我正在尋找如何編寫一個檢索多個JSON對象的循環。

<script type="text/javascript">

  var apiKey = "b0da1774db3d010f62b11f67c4de0667";
  var secret = "0baa4b10c807acc847128599680679a7";

  var lastfm = new LastFM({
    apiKey : apiKey,
    secret : secret,
    cache : undefined
  });

  var lastfm_2 = new LastFM({
    apiKey : apiKey,
    secret : secret,
    cache : undefined
  });

  $(document).ready(function() {
    $("#submit").click(function() {
      var username = $("#username").val();
      var text = "";
      if (username) {
        $("#title").html("Your Most Played Artist by Month");
        $("#title").css("color", "#222");
        // Get top artists for each month
        var topArtistsByMonth = new Array();
        for (var month = 0; month < 12; month++) {
          lastfm.user.getTopArtists({user: username, period: "1month", limit: 15, page: month + 1}, {success: function(data) {
            topArtistsByMonth.push(data.topartists);
            console.log("Month " + month + ": " + data.topartists);
          }});
        }
      } else {
        alert("No username");
      }
    });
  });

</script>

任何幫助將不勝感激,謝謝!

getTopArtists是異步的,所以調用它只會啟動請求; 它不等待它完成。 回調就是你知道什么時候完成的。 這意味着你的for循環並行地將它們全部關閉,然后在完成后收集結果。 但是,由於他們可以按任何順序完成, topArtistsByMonth不能保證topArtistsByMonth處於任何順序。 要解決這個問題,您可能希望使用顯式索引而不是使用push

for(var month = 0; month < 12; month++) {
    // We need to use an anonymous function to capture the current value of month
    // so we don't end up capturing the reference to month that the for loop is
    // using (which, by the time the callbacks complete, will always be 12.)
    (function(month) {
        lastfm.user.getTopArtists({user: username, period: "1month", limit: 15, page: month + 1}, {success: function(data) {
            topArtistsByMonth[month] = data.topartists;
            console.log("Month " + month + ": " + data.topartists);
        }});
    })(month);
}

如果您想知道何時下載了所有數據,您將需要另一個變量來跟蹤到目前為止已完成的數量。 每次調用回調時,你都需要增加它並查看它是否已經命中12。 如果有,則下載所有數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM