[英]How can i loop through 2 arrays at once and assign colours from array to each value of the other array
I have 2 arrays. 我有2个数组。 one is an array of colours and the other is an array of objects (items). 一个是颜色的数组,另一个是对象(项目)的数组。
I want to assign a colour from the first array to each of the objects in the second array. 我想将颜色从第一个数组分配给第二个数组中的每个对象。
array one: 数组一:
var colours = ["#5cbae6", "#b6d957", "#fac364"];
Second array: 第二个数组:
var items = [ itemOne, itemTwo, itemThree, itemFour, itemFive , itemSix.. ];
The items depend on the user. 这些项目取决于用户。 the user can provide one item or 30 items. 用户可以提供一项或30项。 So in some cases the colours will be less than items and in some cases they will be more. 因此,在某些情况下,颜色将小于项目,在某些情况下,颜色将大于项目。
What i want is to loop through "items" array and for each item to assign a colour from the array "colours" 我想要的是遍历“项目”数组,并为每个项目从数组“颜色”分配颜色
example: 例:
item one = 5cbae6
item two = b6d957
item three = fac364
item four = 5cbae6
once the last colour is assigned we should go back to the first colour and assign until all "items" have one colour. 分配完最后一种颜色后,我们应该返回第一种颜色并进行分配,直到所有“项目”都具有一种颜色为止。
pseudo code: 伪代码:
for each object in items loop through array colours and assign one colour to an item. 为项目中的每个对象遍历数组颜色,然后为项目分配一种颜色。 when the third colour is reached start over from the first colour. 当达到第三种颜色时,请从第一种颜色开始。 each item has a property "setColor" and needs the value from "colours" 每个项目都有一个属性“ setColor”,并且需要“ colors”中的值
thanks in advance. 提前致谢。
Use a forEach
to loop through the items
array. 使用forEach
遍历items
数组。 forEach
provides the index of the current item item
, use that index with %
( modulo
operator) to get the index of the equivalent color: forEach
提供当前项目item
的索引,将该索引与%
(取modulo
运算符)一起使用以获取等效颜色的索引:
items.forEach(function(item, index) {
item.setColor( colours[ index % colours.length ] );
});
Explanation of modulo operator: 模运算符的解释:
Let items.length
be 10
and colours.length
be 3
: 令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
where both m
and n
are integers and n != 0
. m % n < n
,其中m
和n
均为整数, n != 0
。
Try this: 尝试这个:
var ans = new Array();
for(var i = 0;i<items.length;++i){
ans[items[i]] = colors[i%colors.length];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.