Pasha
Pasha

Reputation: 166

How can I use right the for loop?

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

Upvotes: 0

Views: 50

Answers (2)

Hamdan Salih
Hamdan Salih

Reputation: 60

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> ");
}

Upvotes: 1

Rusurano
Rusurano

Reputation: 552

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

Upvotes: 1

Related Questions