根据前一个值遍历数组

Go through array based on previous value

本文关键字:一个 遍历 数组      更新时间:2023-09-26

我有一个数组['green', 'red', 'yellow', 'blue']

我想用这些颜色来改变我网站的背景色。但我不想从这个数组中随机取一个颜色。我想按顺序迭代。

所以如果我用getBgColor()得到我的网站的背景色,它打印red,然后我想要一个函数setBgColor(currentColor)来打印yellow。我该怎么做呢?

我想我应该写一些像

function setBgColor(currentColor) {
  var array = ['green', 'red', 'yellow', 'blue'];
  newColor = array[array.indexOf(currentColor) + 1];
}

但这是正确的方法吗?我如何确保从蓝色变为绿色而不超过数组的长度?

可以用%对数组的长度取模

function setBgColor(currentColor) {
    var array = ['green', 'red', 'yellow', 'blue'],
        newColor = array[(array.indexOf(currentColor) + 1) % array.length ];
    // set the new color
    // ...
}

在你的号码中加入一个条件:

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))];

使用包含当前索引的变量,而不是在数组中搜索颜色。使用模运算来增加索引,围绕数组的大小。

var colorIndex = 0;
var colorArray = ['green', 'red', 'yellow', 'blue'];
function setBgColor() {
    colorIndex = (colorIndex + 1) % array.length;
    return colorArray[colorIndex];
}