我正在创建一个自我更新匹配/ fixture脚本,它从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);
});
}
答案 0 :(得分:0)
只需将代码包装在一个$ .each中,它将迭代您的匹配数组:
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);