gpt4 book ai didi

javascript - 当循环中没有更多元素时如何重新开始?

转载 作者:行者123 更新时间:2023-11-30 07:00:14 24 4
gpt4 key购买 nike

假设我“想要”一个仅包含 3 个元素的数组中的 6 个元素。如果到达末尾,则重新开始。

例子:

let arr = ["a", "b", "c"];
let wanted = 5;

for(let i = 0; i < wanted; i++) {
console.log(arr[i]);
}

当然会返回:

a
b
c
undefined
undefined

相反,我需要:

a
b
c
a
b

有没有办法在元素结束后从数组开头开始?

最佳答案

使用 %(Remainder) 得到余数运营商。

console.log(arr[i % arr.length]);

余数将在数组索引范围内。

例如:当i到达

  • 3 => 3 % 3 = 0
  • 4 => 4 % 3 = 1
  • 0 => 0 % 3 = 0

let arr = ["a", "b", "c"];
let wanted = 5;

for (let i = 0; i < wanted; i++) {
console.log(arr[i % arr.length]);
}

关于javascript - 当循环中没有更多元素时如何重新开始?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42828297/

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