我一直在到处寻找解决方案,但我似乎无法在任何地方找到答案!也许我只是错误地表述了我的问题,但是如果索引大于数组长度,我如何循环回到数组的开头?请参阅下面我的代码作为示例:
// Array of colours
let colours = ["#FFBE36", "#FF6447", "#77FF47", "#D547FF", "#FF9E47", "#47DBFF", "#FF4770"];
// For each pack, a background colour from the array above is assigned.
// However, these are fetched from a database so could be more than the
// length of the array
var packs = document.getElementsByClassName("pack-item");
for (var i = 0, len = packs.length; i < len; i++) {
// Here if i is larger than colours.length, loop back to start of
// colours array, e.g colours[8] = "#FFBE36"
packs[i].style.backgroundColor = colours[i];
}
我希望这是有道理的?如果您希望我以不同的措辞/更详细地解释,请告诉我!
谢谢:)
最佳答案
您可以使用模运算符 (%) 来完成此操作,如下所示。这将使计数器保持正确的长度并且颜色保持顺序。
// Array of colours
let colours = ["#FFBE36", "#FF6447", "#77FF47", "#D547FF", "#FF9E47", "#47DBFF", "#FF4770"];
// For each pack, a background colour from the array above is assigned.
// However, these are fetched from a database so could be more than the
// length of the array
var packs = document.getElementsByClassName("pack-item");
for (var i = 0, len = packs.length; i < len; i++) {
// Here if i is larger than colours.length, loop back to start of
// colours array
packs[i].style.backgroundColor = colours[i % colours.length];
}
关于当索引大于数组长度时,Javascript 循环回到数组开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64760623/