繁体   English   中英

我想在javascript中有一个颜色列表

[英]I want to have a list of color in javascript

我想在javascript中有一个颜色列表,我有一个动作,它将从列表中获取第一种颜色,并以某种方式记住他已采取第一种颜色。 所以下次当我再次执行相同的动作时,他将从列表中获取下一个颜色,依此类推。

如何实现这一目标。

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

var colors = ['red', 'blue', 'green', 'yellow'];
alert(colors.shift());
alert(colors.shift());
// and so on ...
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'
}

这可以使用数组方法轻松完成

//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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM