简体   繁体   中英

How to make a repeat pattern in for loop Javascript?

I'd like to make a repeat pattern to color background. But after i is over colors.length it starts not to change background color because for example colors[3] does not exists. But I'd like to make colors[i] return back 0 again until first for loop completed.

const arr = document.getElementById('collection');
const colors = ['#FFC6C6', '#A4BDFF', '#F9F9F9'];

for (let i = 0; i < arr.children.length; i++) {
    arr.children[i].style.background = colors[i];
}

Read about modulo

const arr = document.getElementById('collection');
const colors = ['#FFC6C6', '#A4BDFF', '#F9F9F9'];

for (let i = 0; i < arr.children.length; i++) {
    arr.children[i].style.background = colors[i % colors.length];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM