gpt4 book ai didi

javascript - 如何使用 Javascript 简单地循环遍历数组?

转载 作者:行者123 更新时间:2023-11-28 16:58:54 24 4
gpt4 key购买 nike

我有一个由第三方 API 以 JSON 形式返回的数据集。

现在我想循环遍历数据并在前端填充排行榜(使用数组中的 11 个键:值)。

我已经将对象转换为数组(var stands)并定义了一个空变量“rank”。但现在我真的不知道如何继续,其他教程只会增加我的困惑。

我是否需要创建 11 个空数组来将所需的数据放入其中,然后使用"new"数组填充 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 返回未定义(我尝试打印数组中的所有 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>

[...]

enter image description here

最佳答案

从表面上看,这有点奇怪的响应格式。问题是 stands 不是结果数组,它是一个以单个数组作为唯一元素的数组,而数组就是包含结果的数组。

如果它始终具有单个条目的数组,则改为:

var standings = response.api.standings;

你需要

var standings = response.api.standings[0];

但是您需要查看您正在使用的 JSON feed 的文档,以了解为什么它有这个额外的层,您可能需要一个嵌套循环,例如:

for (const standing of response.api.standings) {
for (const entry of standing) {
console.log(entry.teamName);
}
}
<小时/>

有关循环数组的各种方法的更多信息,请参见 my answer here .

关于javascript - 如何使用 Javascript 简单地循环遍历数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58247811/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com