问题描述
我基本上是在尝试构建一个显示来自 API 的数据的站点。我使用以下异步函数来获取数据:
async function getapi(url) {
//store response
const response = await fetch(url);
//store data in JSON
var data = await response.json();
getData(data);
}
for(let r of data.rounds) {
let round = r.names.shortName;
let nextRound = //no idea how to get the name of the next round
这将返回我当前所在的回合(第一个循环中的 R1)。基本上我想要的是下一轮的shortName。 (所以我想在第一个循环中使用 R2)。 有没有办法访问下一个循环的数据?
console.log(r) 显示: console.log of R
解决方法
为了更干净的实现
data.rounds.map((item,index,self) => {
let round = r.names.shortName;
let nexObj = self[index+1]
})
,
使用 for
循环代替 forof
循环。它允许您检查数组的下一个索引并按如下方式使用它。
for (let i = 0; i < data.rounds.length; i++) {
const round = data.rounds[i];
const name = r.names.shortName;
let nextRound = data.rounds[i + 1];
if (nextRound) {
// your code here
}
}
,
我认为带有索引访问的普通 for
示例显然更简洁。只是为了好玩,或者如果您真的坚持使用 for of
(一些没有随机访问的可迭代数据结构)。
let prevRound
for (let r of data.rounds) {
if (prevRound) name = prevRound.names.shortName
// nextRound = r at this point,obviously
...
prevRound = r
}
,
如果您需要一个循环中的下一个元素,您可以使用索引,因为人们已经回答了。如果您的意思是如何进行迭代 - 您不需要进行“i++”迭代等。 for.. of 循环将在主体完成后开始下一个循环。
替代方案:
for(let r of data.rounds) {
let round = r.names.shortName;
let nextIndex = data.indexOf(r) + 1;
if(nextIndex <= data.length){
let nextRound = data[nextIndex];
}
}