【问题标题】:Loop through list of colors while maintaining order在保持顺序的同时循环遍历颜色列表
【发布时间】:2021-12-28 16:22:03
【问题描述】:

假设我有一个颜色列表,例如

let ListOfColors = ["Red", "Blue", "Yellow"];

我需要通过一个接收许多要打印的元素的函数对其进行迭代,使其行为如下:

如果要打印的元素数量为 5,则应该打印

Red
Blue
Yellow
Red
Blue

如你所见,一旦当前迭代超过颜色总数,它就会重新开始。

目前,这就是我所拥有的:

function TestColorIteration(NumberOfTimesToIterate)
{
    let ListOfColors = ["Red", "Blue", "Yellow"];

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

但它不会再次开始循环,它会打印 undefined。

【问题讨论】:

    标签: javascript arrays loops


    【解决方案1】:

    最简单的解决方案是使用两个循环。

    function TestColorIteration(NumberOfTimesToIterate)
    {
        let ListOfColors = ["Red", "Blue", "Yellow"];
        var fullRounds = Math.floor(NumberOfTimesToIterate/ListOfColors.length)
        var remainder  = NumberOfTimesToIterate%ListOfColors.length
    
        for(let i = 0; i< fullRounds; i++)
        {
           console.log(ListOfColors[0])
           console.log(ListOfColors[1])
           console.log(ListOfColors[2])
        }
    
        for(let i = 0; i< remainder; i++)
        {
           console.log(ListOfColors[i])
        }
    }
    
    

    【讨论】:

      【解决方案2】:

      使用 while 循环更容易实现。

      发生的情况是您到达数组中的最后一个元素,然后尝试获取 更多 个元素,但没有更多元素反过来给您未定义。

      一旦达到数组中的最大元素,您需要重置数组中的“位置”。

      function TestColorIteration(NumberOfTimesToIterate)
      {
          let ListOfColors = ["Red", "Blue", "Yellow"];
          
          let counter = 0;
          let listElem = 0;
          
          while(counter < NumberOfTimesToIterate)
          {
            console.log(ListOfColors[listElem]);
            
            counter++;
            listElem++;
            
            if(counter == ListOfColors.length)
            {
              listElem = 0;
            }
            
          }
      
      }
      
      TestColorIteration(5);

      【讨论】:

        【解决方案3】:

        模运算符 (%) 返回整数除法后的余数。

        function TestColorIteration(NumberOfTimesToIterate)
        {
            let ListOfColors = ["Red", "Blue", "Yellow"];
            let Count = ListOfColors.length;
        
            for(let i = 0; i< NumberOfTimesToIterate; i++)
            {
               console.log(ListOfColors[i % Count])
            }
        }
        

        您看到undefined 是因为i 索引增长到大于数组的长度。 尝试访问数组“边界”之外的元素将返回 undefined

        【讨论】:

        • 这确实适用于这个例子,因为列表不为空。需要注意的是 % 执行除法以返回余数,所以更一般地,如果数组恰好为空,则 count 将为零,因此 i % count 将是 NaN
        猜你喜欢
        • 2014-09-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-15
        • 1970-01-01
        • 2013-06-22
        相关资源
        最近更新 更多