0

I have an array ['green', 'red', 'yellow', 'blue'].

I want to change the background color of my website using these colors. But I don't want to just take a random color from this array. I want to iterate it in order.

So if I get the background color of my website with getBgColor() and it prints red, then I want a function setBgColor(currentColor) to print yellow. How do I do this?

I guess I should do something like

function setBgColor(currentColor) {
  var array = ['green', 'red', 'yellow', 'blue'];

  newColor = array[array.indexOf(currentColor) + 1];
}

but is this the right approach? And how do I make sure that I go from blue to green and thus not exceeding the length of the array?

3 Answers 3

5

You could use modulo % with the length of the array.

function setBgColor(currentColor) {
    var array = ['green', 'red', 'yellow', 'blue'],
        newColor = array[(array.indexOf(currentColor) + 1) % array.length ];
    // set the new color
    // ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

nice answer - newColor needs to be returned
0

Just include a conditional in your number to add:

var array = ['green', 'red', 'yellow', 'blue'],
    last_index = array.length - 1,
    thisIndex = array.indexOf(currentColor);

return array[thisIndex + (thisIndex !== last_index ? 1 : (-1 * last_index))];

Comments

0

Use a variable that contains the current index, rather than searching for the color in the array. Use modular arithmetic to increment the index, wrapping around at the array size.

var colorIndex = 0;
var colorArray = ['green', 'red', 'yellow', 'blue'];

function setBgColor() {
    colorIndex = (colorIndex + 1) % array.length;
    return colorArray[colorIndex];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.