2021年4月28日星期三

Loop through an array starting at a dynamically-generated index

Sorry if the title doesn't accurately capture my question; wasn't sure how to write this in a single sentence.

Problem description: Let's say I have an array of colors and a bunch of divs. I want to cycle the div background color through the array colors, but also making sure each div starts at a different position in the color array.

Example: my color array is [red, blue, yellow, green]. The first div color starts as red, then cycles through blue, yellow, green before going back to red. Div2 starts as blue, then goes yellow, green, red, blue, and so on for as many div elements as I have.

The two potential solutions I can imagine are:

  1. Would I have to generate a new color array for each div? (maybe by adding 1 to a counter and doing a splice or push or pop operation)
  2. Could I loop through the original array, just starting from a different position for each div? (dynamically generate an offset based on its position - 1st div, 2nd, 3rd, etc.)

Are these both viable ways to solve the problem?

https://stackoverflow.com/questions/67309580/loop-through-an-array-starting-at-a-dynamically-generated-index April 29, 2021 at 08:36AM

没有评论:

发表评论