使用带有模数运算符的数组索引确定值

Determine value using array index with modulus operator

我讨厌数学。接下来的几个小时我可以坐在这里尝试解决这个问题,但我希望有半个大脑的人可以帮助我解决这个使用模数的基本数学问题。

let bricks = [{id: 1}, {id: 2}, {id: 3}, {id: 4}, {id: 5}]; // ...etc

for (var i = 0; i < bricks.length; i++) {
  // determine colour using modulus
  bricks[i].colour = help;
}

我需要第一块砖是红色的,第二块砖是绿色的,第三块砖是蓝色的。然后对 bricks 数组中的项目重复该模式。

一个有点尴尬的问题,但如果您能提供帮助,我们将不胜感激!

您可以采用一个数组和索引,其中索引对颜色数组的长度取模。

const colors = ['red', 'green', 'blue'];

for (var i = 0; i < bricks.length; i++) {
    bricks[i].colour = colors[i % colors.length];
}

您可以使用 array#map 并对颜色数组的长度取模。

let bricks = [{id: 1}, {id: 2}, {id: 3}, {id: 4}, {id: 5}],
    colors = ['red','green','blue'],
    result = bricks.map(({id},i) => ({id, color : colors[i%colors.length]}));
console.log(result);