繁体   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