2011-12-20 73 views
0

我想要在javascript中有一个颜色列表,我有一个动作,它将从列表中获取第一个颜色,并以某种方式记住他已采取第一种颜色。所以下次再次执行同样的操作时,他会从列表中选取下一个颜色等等。我想在javascript中有一个颜色列表

如何做到这一点?

回答

0
var colors = ['red', 'green', 'blue']; 
while(colors.length) { 
    var color = colors.shift(); 
    // do something with color. They will come in the order 'red','green','blue' 
} 
2

将你的颜色放在一个数组中,并使用它的pop()或shift()方法获取该数组的第一个或最后一个元素。

var colors = ['red', 'blue', 'green', 'yellow']; 
alert(colors.shift()); 
alert(colors.shift()); 
// and so on ... 
+0

有什么呼叫colors.remove? – user882196 2011-12-20 08:10:45

+0

shift()和unshift()在返回它之后实际从原始数组中移除条目。 – ChrisR 2011-12-20 08:35:22

0

这可以很容易地与阵列方法来完成

//initialize your list of colors 
var unchosenColors = ['#fff', '#456', '#987878'] 
    , chosenColors = [] 

//you want to call this when the user chooses a color, (click, keypress, etc) 
function chooseColor() { 
    //remove the first unchosen color and put it in the list of chosen colors 
    chosenColors.unshift(unchosenColors.shift()) 
} 
//then, to get the most recently chosen color: 
chosenColors[0] 
+0

尝试http://jsfiddle.net/Mp3cZ/。它不能工作。 – user882196 2011-12-20 09:18:00

+0

http://jsfiddle.net/Mp3cZ/5/ 你必须调用选择颜色方法,否则他们没有选择一种颜色。你可能想要做那个onClick。当用户执行选择颜色的动作时。 – coderzach 2011-12-20 10:12:40

相关问题