[英]How can I simply loop through an array using Javascript?
我有一个由第三方 API 作为 JSON 返回的数据集。
现在我想遍历数据并在我的前端填充一个排行榜(使用数组中的 11 个键:值)。
我已经将 object 转换为数组(var standings
)并定义了一个空变量“rank”。 但现在我真的被困在如何继续下去,其他教程只会增加我的困惑。
我是否需要创建 11 个空的 arrays 来获取所需的数据,然后使用“新的”arrays 填充 html? 可能这个任务可以通过“25-line-all-in-super-loop-solution”来处理。
这是我的 Javascript(掌声:):
$.ajax({
method: "GET",
async: "True",
dataType: "json",
url: "https://cors-anywhere.herokuapp.com/https://www.api-football.com/demo/api/v2/leagueTable/" + league_id,
success: function(response) {
var standings = response.api.standings;
for (let i = 0; i < standings.length; i++) {
var rank = [];
console.log(standings[i].teamName);
}
console.log 返回undefined
(我试图打印数组中的所有 20 个团队名称)。
这是 JSON 数据(它返回 1 个结果 = 1 个联赛表,包括数组中的所有球队以及其他数据)
{
"api": {
"results": 1,
"standings": [
[
{
"rank": 1,
"team_id": 85,
"teamName": "Paris Saint Germain",
"logo": "https://media.api-football.com/teams/85.png",
"group": "Ligue 1",
"forme": "DLWLL",
"description": "Promotion - Champions League (Group Stage)",
"all": {
"matchsPlayed": 35,
"win": 27,
"draw": 4,
"lose": 4,
"goalsFor": 98,
"goalsAgainst": 31
},
"home": {
"matchsPlayed": 18,
"win": 16,
"draw": 2,
"lose": 0,
"goalsFor": 59,
"goalsAgainst": 10
},
"away": {
"matchsPlayed": 17,
"win": 11,
"draw": 2,
"lose": 4,
"goalsFor": 39,
"goalsAgainst": 21
},
"goalsDiff": 67,
"points": 85,
"lastUpdate": "2019-05-04"
},
{...}
]
]
}
}
以及要填充的 HTML 部分(但这将是第 2 步)
<div class="fifthRow">
<div class="column">
<div class="table" id="rank">
<div><p></p></div>
[...]
<div><p></p></div>
</div>
<div class="table" id="logo">
<div><p>Rank</p></div>
<div><p></p></div>
[...]
<div><p></p></div>
</div>
[...]
从表面上看,这有点奇怪的响应格式。 问题是, standings
不是结果数组,它是一个数组,只有一个数组作为它的唯一元素,而那个数组就是包含结果的数组。
如果它始终是一个包含单个条目的数组,那么而不是:
var standings = response.api.standings;
你需要
var standings = response.api.standings[0];
但是您需要查看您正在使用的 JSON 提要的文档,以了解为什么它有这个额外的层,您可能需要一个嵌套循环,例如:
for (const standing of response.api.standings) {
for (const entry of standing) {
console.log(entry.teamName);
}
}
更多关于在我的回答中循环通过 arrays 的各种方法。
问题在于 var 排名 = response.api.standings;
实际上排名是数组数组。
所以像这样访问它
var standings = response.api.standings[0];
与实际上似乎是嵌套数组的响应格式相关的附加小答案。 我使用response.data.api.standings[0][0]
处理输入数组
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.