【问题标题】:How can i loop through 2 arrays at once and assign colours from array to each value of the other array如何一次循环遍历 2 个数组并将数组中的颜色分配给另一个数组的每个值
【发布时间】:2023-03-22 23:00:01
【问题描述】:

我有 2 个数组。一个是颜色数组,另一个是对象(项目)数组。

我想将第一个数组中的颜色分配给第二个数组中的每个对象。

数组一:

var colours = ["#5cbae6", "#b6d957", "#fac364"];

第二个数组:

var items = [ itemOne, itemTwo, itemThree, itemFour, itemFive , itemSix.. ];

项目取决于用户。用户可以提供一项或 30 项。所以在某些情况下,颜色会比物品少,而在某些情况下,颜色会更多。

我想要的是遍历“items”数组,并为每个项目从数组“colors”中分配一种颜色

示例:

item one = 5cbae6
item two = b6d957
item three = fac364
item four = 5cbae6

一旦分配了最后一种颜色,我们应该回到第一种颜色并分配,直到所有“项目”都具有一种颜色。

伪代码:

对于项目中的每个对象,循环遍历数组颜色并将一种颜色分配给项目。当达到第三种颜色时,从第一种颜色重新开始。每个项目都有一个属性“setColor”,需要来自“colors”的值

提前致谢。

【问题讨论】:

    标签: javascript jquery arrays function loops


    【解决方案1】:

    使用forEach 循环遍历items 数组。 forEach 提供当前项目item 的索引,将该索引与%modulo 运算符)一起使用以获得等效颜色的索引:

    items.forEach(function(item, index) {
        item.setColor( colours[ index % colours.length ] );
    });
    

    模运算符说明:

    items.length10colours.length3

    index === 0   =>   index % colours.length === 0 % 3 === 0   =>   first colour
    index === 1   =>   index % colours.length === 1 % 3 === 1   =>   second colour
    index === 2   =>   index % colours.length === 2 % 3 === 2   =>   third colour
    index === 3   =>   index % colours.length === 3 % 3 === 0   =>   first colour
    index === 4   =>   index % colours.length === 4 % 3 === 1   =>   second colour
    index === 5   =>   index % colours.length === 5 % 3 === 2   =>   third colour
    index === 6   =>   index % colours.length === 6 % 3 === 0   =>   first colour
    index === 7   =>   index % colours.length === 7 % 3 === 1   =>   second colour
    index === 8   =>   index % colours.length === 8 % 3 === 2   =>   third colour
    index === 9   =>   index % colours.length === 9 % 3 === 0   =>   first colour
    

    m % n < n 其中mn 都是整数,n != 0

    【讨论】:

      【解决方案2】:

      试试这个:

      var ans = new Array();
      for(var i = 0;i<items.length;++i){
          ans[items[i]] = colors[i%colors.length];
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-22
        相关资源
        最近更新 更多