Reputation: 1721
I want to have a list of colors in javascript and I have a action which will take first color from the list and somehow remembers that he has taken the first color. So next time when i perform the same action again he will take the next color from list and so on.
How to achieve this.?
Upvotes: 0
Views: 3218
Reputation: 388
This can be done easily with array methods
//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]
Upvotes: 0
Reputation: 14447
Put your colors in an array and use the pop() or shift() methods on it to get the first or last element from that array.
var colors = ['red', 'blue', 'green', 'yellow'];
alert(colors.shift());
alert(colors.shift());
// and so on ...
Upvotes: 2
Reputation: 17434
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'
}
Upvotes: 0