2016-09-23 48 views
0

我有一个数组['green', 'red', 'yellow', 'blue']根据以前的值经过数组

我想改变我的网站使用这些颜色的背景颜色。但我不想从这个数组中随机取色。我想按顺序迭代它。

所以,如果我得到我的网站getBgColor()的背景颜色和它打印red,那么我想一个函数setBgColor(currentColor)打印yellow。我该怎么做呢?

我想我应该这样做

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

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

但是这是正确的做法?我如何确保我从蓝色变为绿色,从而不超过阵列的长度?

回答

5

您可以使用modulo%与数组长度。

function setBgColor(currentColor) { 
    var array = ['green', 'red', 'yellow', 'blue'], 
     newColor = array[(array.indexOf(currentColor) + 1) % array.length ]; 
    // set the new color 
    // ... 
} 
+0

不错的答案 - ** newColor **需要退回 –

+0

没错。但是这部分不见了......无论如何。 :) –

0

只需在您的号码有条件补充:

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))]; 
0

使用包含当前索引,而不是搜索数组中颜色的变量。使用模块化算术来增加索引,并以数组大小换行。

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

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