Home > Mobile >  How can I use right the for loop?
How can I use right the for loop?

Time:01-08

I have such a task. I want to create 15 divs and I want to take the background colors of these divs from the array. But here only divs are created according to 5 colors, the color of the others is undefined. How can I cycle the colors?

let color = ["yellow", "green", "red", "blue", "orange"];

for (var i = 0; i <= 15; i  ) {
    document.write("<div style='background:"   color[i]   "'></div> ");
}

enter image description here

CodePudding user response:

Simple as it is, use modulo arithmetic.

Instead of color[i], use color[i % color.length], and it will work as you want.

Taking the remainder from the division of the current index by the length of the array will bind it to the range [0;length), which can allow you to repeat all array indices infinitely many times. See for yourself:

i i % 5
0 0
1 1
2 2
3 3
4 4
5 0
6 1
7 2
8 3
9 4
10 0
11 1
12 2
13 3
14 4
15 0

CodePudding user response:

try this

let color = ["yellow", "green", "red", "blue", "orange"];


for (var i = 0; i <= 15; i  ) {
    document.write("<div style='background:"   color[i % (color.length)]   "'></div> ");
}

  • Related