【问题标题】:Javascript Loop Back To Start Of Array When Index Is Larger Than Array Length当索引大于数组长度时,Javascript 循环回到数组的开头
【发布时间】:2021-02-21 21:39:45
【问题描述】:

我一直在到处寻找解决方案,但我似乎无法在任何地方找到答案!也许我只是把我的问题用错了,但是如果索引大于数组长度,我该如何循环回到数组的开头?请参阅下面的代码示例:

// 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];
}

我希望这是有道理的?如果您希望我用不同的方式/更详细地解释它,请告诉我!

谢谢:)

【问题讨论】:

    标签: javascript arrays loops indexing


    【解决方案1】:

    您可以使用模运算符 ( % ) 来执行此操作,如下所示。这将使计数器保持正确的长度,并且颜色保持有序。

    // 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];
    }
    

    【讨论】:

    • @Samathingamajig 这可能是正确的答案。假设用户不想要无限循环,只是想处理这样的情况,比如有 21 个包,它们只有 7 种颜色,这个逻辑会为每个包分配一个颜色,当它到达末尾时循环颜色颜色数组。
    • 完美!谢谢!
    【解决方案2】:

    使用while 循环更容易,因此您拥有递增的colorPointer,如果它等于数组的真实长度colors.length-1,因为它是零索引的,它将返回从头到尾。

    // 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
    let counter = 0;
    let colorPointer = 0;
    var packs = document.getElementsByClassName("pack-item");
    while(counter < packs.length) {
      // Here if i is larger than colours.length, loop back to start of 
        // colours array 
        packs[counter].style.backgroundColor = colours[colorPointer];
        counter++;
        colorPointer++;
        if(colorPointer === colours.length-1){
          colorPointer = 0;
        }
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-22
      • 2017-08-26
      • 1970-01-01
      • 2017-04-17
      • 1970-01-01
      • 2023-04-03
      • 2021-10-25
      • 2020-07-14
      相关资源
      最近更新 更多