我正在编写一些代码,其中有两个变量,其中有几个不同的团队。我是 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);}它可以毫无问题地打印我的主队列表,但我确实正在寻找一个可以打印我的主队和客队的循环,列表大小是相同的并且始终如此。
2 回答
RISEBY
TA贡献1856条经验 获得超5个赞
只需使用索引 for 循环
for(let i = 0;i < home_team.length; i++) { console.log(home_team[i] + "VS" + away_team[i]); }
您还可以使用forEach
home_team.forEach((item, index) => console.log(item + "VS" + away_team[index]));
PIPIONE
TA贡献1829条经验 获得超9个赞
如果两个数组包含相同数量的项目,那么您可以使用普通的 for 循环来访问具有相同索引的每个项目,如下所示 -
let home_team = ["A", "B", "C"];
let away_team = ["D", "E", "F"];
for(let i=0; i<home_team.length; i++){
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--){
console.log(`${home_team[i]} VS ${away_team[j]}`);
}
添加回答
举报
0/150
提交
取消