猿问

使用两个变量的 for 循环?

我正在编写一些代码,其中有两个变量,其中有几个不同的团队。我是 JS 新手,似乎无法理解如何在同一个 for 循环中打印两个变量的值。


let jsonData = pm.response.json();

let home_team = []

let away_team = []

let home_team_id = []

let away_team_id = []

//console.log(jsonData)

jsonData.games.forEach((b)=>{

    home_team.push(b.home.name)

    away_team.push(b.away.name)


})


pm.environment.set("Home_Team",home_team)

pm.environment.set("Away_Team",away_team)

//console.log(pm.environment.get("Home Team"))

//console.log(pm.environment.get("Away Team"))


for (const element of home_team) {

  console.log(element + "VS" + away_team);

}

现在我知道上面的代码不会运行,我只是显示我想要打印到控制台的内容,我不知道如何添加在同一循环中引用away_team 的第二个元素。话虽如此,当我将 for 循环设置为


for (const element of home_team) {

  console.log(element);

}

它可以毫无问题地打印我的主队列表,但我确实正在寻找一个可以打印我的主队和客队的循环,列表大小是相同的并且始终如此。


守候你守候我
浏览 124回答 2
2回答

RISEBY

只需使用索引 for 循环for(let&nbsp;i&nbsp;=&nbsp;0;i&nbsp;<&nbsp;home_team.length;&nbsp;i++)&nbsp;{ &nbsp;&nbsp;console.log(home_team[i]&nbsp;+&nbsp;"VS"&nbsp;+&nbsp;away_team[i]); }您还可以使用forEachhome_team.forEach((item,&nbsp;index)&nbsp;=>&nbsp;console.log(item&nbsp;+&nbsp;"VS"&nbsp;+&nbsp;away_team[index]));

PIPIONE

如果两个数组包含相同数量的项目,那么您可以使用普通的 for 循环来访问具有相同索引的每个项目,如下所示 -let home_team = ["A", "B", "C"];let away_team = ["D", "E", "F"];for(let i=0; i<home_team.length; i++){&nbsp; console.log(`${home_team[i]} VS ${away_team[i]}`);}或者,您也可以在 for 循环中使用多个计数器,如下所示(尽管您现在不需要这个 -let home_team = ["A", "B", "C"];let away_team = ["D", "E", "F"];for(let i=0,j=2; i<home_team.length; i++, j--){&nbsp; console.log(`${home_team[i]} VS ${away_team[j]}`);}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答