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

I want to have a list of color in javascript

本文关键字:有一个 颜色 列表 javascript      更新时间:2023-09-26

我想在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]
相关文章: