最后一次迭代后 setInterval returns undefined

After last iteration setInterval returns undefined

我正在尝试让 background-color 在 X 时间后进行交换,并且它在最后一次迭代后工作但是步长设置为 0,我得到的是 undefined 我可以弄清楚为什么:/

const foo = () => {
  const colors = [{
      primary: 'LightGreen',
      secondary: '#7fe27f'
    },
    {
      primary: "Gold",
      secondary: '#efc900'
    },
    {
      primary: "#1590FF",
      secondary: '#0479FF'
    },
    {
      primary: "#00BFFF",
      secondary: '#06ace3'
    }
  ]
  let step = -1
  return setInterval(() => {
    step === colors.length ? step = 0 : step++
      return console.log(colors[step]);
  }, 2000)
}

知道为什么会这样吗?我该如何解决?

step等于colors.length - 1时,你将执行step++,这将使step === colors.length。然后您将访问 colors[colors.length]undefined.

您必须检查step === colors.length - 1是否符合您的条件。

但更好的解决方案是使用余数运算符。你可以这样做:

console.log(colors[step++ % colors.length]);