Reputation: 11049
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?
Upvotes: 0
Views: 48
Reputation: 781721
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];
}
Upvotes: 0
Reputation: 386680
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
// ...
}
Upvotes: 5
Reputation: 7884
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))];
Upvotes: 0