循环JQuery数组

Loop through JQuery array

本文关键字:数组 JQuery 循环      更新时间:2023-09-26

我正在创建一个自更新的匹配/固定脚本,它从自动更新的JSON脚本返回数据。然而,JSON脚本包括3个实时数组、即将到来的数组和最近的数组。我如何循环遍历所有这些数组,而不是只匹配活动的[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);


  });
}

只需将代码包装在一个$.中,每个$.将迭代匹配数组:

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);