簡體   English   中英

遍歷JQuery數組

[英]Loop through JQuery array

我正在創建一個自我更新的匹配/裝置腳本,該腳本從自動更新的JSON腳本返回數據。 但是,JSON腳本包含3個實時,即將到來和最近的數組。 我如何遍歷所有這些數組,而不僅僅是live [matchs [0]]? 我試過使用循環,但無法循環通過功能?

var lastLoadedMatch = 0,
  ajaxInterval = 5000;

$(function() {
  getMatches();

});

function getMatches(lastId) {
  $.getJSON('data.json', function(resp) {
    console.log(JSON.stringify(resp));
    var matches = [resp.live, resp.upcoming, resp.recent];



    if (lastId) {
      matches[0] = matches[0].filter(
        function(match) {
          return match.id > lastId;
        });
    }

    if (matches[0].length) {
      $.each(matches[0], function(_, match) {
        console.log([match.match_id,lastLoadedMatch ])
        if (match.match_id > lastLoadedMatch) {
          lastLoadedMatch = match.match_id
        }
        if ($.trim(match.game) == "lol") {
        $('#part-1').append(matchHtml(this))
        } else if ($.trim(match.game) == "counterstrike") {
           $('#part-2').append(matchHtml(this))
        } else if ($.trim(match.game) == "dota2") {
           $('#part-3').append(matchHtml(this))
        } else if ($.trim(match.game) == "hearthstone") {
           $('#part-4').append(matchHtml(this))
        }


      });

    }else{

    }

    setTimeout(function() {
        getMatches(lastLoadedMatch);
      }, ajaxInterval);




  });
}

只需將您的代碼包裝在另一個$ .each中,這將迭代您的matchs數組:

var matches = [resp.live, resp.upcoming, resp.recent];

$.each(matches, function(_, match) {

    if (lastId) {
      match = match.filter(
        function(match) {
          return match.id > lastId;
        });
    }

    if (match.length) {
      $.each(match, function(_, match) {
         ...

或者您可以串聯數組:

var matches = resp.live.concat(resp.upcoming, resp.recent);

暫無
暫無

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

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