我有 2 个数组。一个是颜色数组,另一个是对象(项目)数组。
我想将第一个数组中的颜色分配给第二个数组中的每个对象。
数组一:
var colours = ["#5cbae6", "#b6d957", "#fac364"];
第二个数组:
var items = [ itemOne, itemTwo, itemThree, itemFour, itemFive , itemSix.. ];
项目取决于用户。用户可以提供一项或 30 项。因此,在某些情况下,颜色会比物品少,而在某些情况下,它们会更多。
我想要的是遍历“items”数组并为每个项目从数组“colours”中分配一种颜色
例子:
item one = 5cbae6
item two = b6d957
item three = fac364
item four = 5cbae6
一旦分配了最后一种颜色,我们应该回到第一种颜色并分配,直到所有“项目”都有一种颜色。
伪代码:
对于 items 中的每个对象遍历数组颜色并为项目分配一种颜色。当达到第三种颜色时,从第一种颜色开始。每个项目都有一个属性“setColor”并且需要来自“colours”的值
提前致谢。
使用 aforEach
循环遍历items
数组。forEach
提供当前 item 的索引item
,使用该索引和%
( modulo
operator) 来获取等效颜色的索引:
items.forEach(function(item, index) {
item.setColor( colours[ index % colours.length ] );
});
模运算符的解释:
让items.length
是10
和colours.length
成为3
:
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
其中m
和n
都是整数和n != 0
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句