JS中使用for...of循环时如何获取下一个迭代对象的属性值
原生for...of循环没有直接获取下一轮迭代项的内置语法,你可以通过以下两种方案实现需求:
方案1:使用带索引的普通for循环(最直观)
直接通过数组下标访问当前项和下一项,代码示例:
function getData(data) { const rounds = data.rounds; // 遍历所有轮次 for (let i = 0; i < rounds.length; i++) { const currentRoundName = rounds[i].names.shortName; // 处理边界:最后一轮不存在下一轮,可根据业务需求设置默认值 const nextRoundName = i < rounds.length - 1 ? rounds[i+1].names.shortName : null; // 你的后续业务逻辑 } }
方案2:保留for...of写法,搭配entries()获取索引
如果你不想修改for...of的写法,可以调用数组的entries()方法同时拿到当前项的索引和值,再通过索引取下一项,代码示例:
function getData(data) { // entries()返回 [索引, 当前项] 的迭代器 for (const [i, r] of data.rounds.entries()) { let round = r.names.shortName; // 同样需要处理最后一轮的边界情况 let nextRound = i < data.rounds.length - 1 ? data.rounds[i+1].names.shortName : undefined; // 你的后续业务逻辑 } }
注意:一定要加边界判断逻辑,否则遍历到最后一轮时访问不存在的下一项属性会抛出运行时异常。
内容的提问来源于stack exchange,提问作者J.Doe
相关产品推荐
相关产品推荐

