2016-09-23 24 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]; 
} 
相關問題