如何遍历两组数字?

How can I loop through two sets of numbers?

我有两个小谜题,我不太明白!

我需要无限循环遍历两组数字,先是一组,然后是另一组,每组之间有 10 秒的停顿,其中两个值都返回 -1。两者都从 -1 开始,都上升到 2。

firstIndex = -1
secondIndex = -1

我可以循环使用第一个数字:

setInterval(() => {
  if (firstIndex === 2) {
    firstIndex = 0;
  } else {
    firstIndex++
  }
}, 10000);

但我不知道如何在这些值之间切换。

所以结果会是……

-1, -1 (10 secs) starting values
0, -1 (10 secs)
-1, -1 (10 secs) back to start
1, -1 (10 secs)
-1, -1 (10 secs) back to start
2, -1 (10 secs)
-1, -1 (10 secs) back to start
-1, 0 (10 secs)
-1, -1 (10 secs) back to start
-1, 1 (10 secs)
-1, -1 (10 secs) back to start
-1, 2 (10 secs)
-1, -1 (10 secs) back to start
…and repeat

请帮忙:)

如果可能 (!) 它是否也能够创建一个循环来像这样从左到右切换……

-1, -1 (10 secs) starting values
0, -1 (10 secs)
-1, -1 (10 secs) back to start
-1, 0 (10 secs)
-1, -1 (10 secs) back to start
1, -1 (10 secs)
-1, -1 (10 secs) back to start
-1, 1 (10 secs)
-1, -1 (10 secs) back to start
2, -1 (10 secs)
-1, -1 (10 secs) back to start
-1, 2 (10 secs)
-1, -1 (10 secs) back to start
…and repeat

您可以获取一个数组并使用给定索引递增该值直到最大值,然后更改索引以递增另一个索引,依此类推。

let
    data = [0, 0],
    index = 0;

setInterval(() => {
    if (++data[index] > 2) {
        data[index] = 0;
        index = 1 - index;
    }
    console.log(...data);
}, 500);

我会将这些索引存储在一个数组中,而不是两个变量中。这样它就很容易扩展到 3 个或更多索引。

这是一个实现,其中有 3 个而不是 2 个索引(为了更好地演示这个想法)。在定时器回调的任何开始,将只有一个不等于 -1 的索引:

var max = 2;
var indices = [-1, -1, max]; // put max in last entry

setInterval(() => {
    let i = indices.findIndex(n => n !== -1);
    indices[i]++;
    if (indices[i] > max) {
        indices[i] = -1;
        indices[(i + 1) % indices.length] = 0;
    }
    console.log(...indices);
}, 300);

此代码中的赋值对数组元素进行了更新。意识到这里使用了一个数组而不是两个(或更多)索引变量(firstIndexsecondIndex),因为这是更好的做法。

因此,在本应使用 firstIndex 的地方使用 indices[0],在本应使用 secondIndex 的地方使用 indices[1]

如果您真的非常想将它们用于变量,则每次进行更新时都将它们初始化,就像这样(这里我们只使用两个索引而不是上面的三个):

var max = 2;
var indices = [-1, max]; // put max in last entry

setInterval(() => {
    let i = indices.findIndex(n => n !== -1);
    indices[i]++;
    if (indices[i] > max) {
        indices[i] = -1;
        indices[(i + 1) % indices.length] = 0;
    }
    let [firstIndex, secondIndex] = indices;
    console.log(firstIndex, secondIndex);
}, 300);

左右切换

当您向您的问题添加另一个场景时,这里有一些观察结果:

  • 我们可以使用一个辅助变量 i 从 0 开始递增 1
  • 当该索引为 偶数(不是奇数)时,输出应始终为 -1,-1
  • 当该索引为奇数时,其中一个索引应不同于-1。
  • 由于该索引从一侧切换到另一侧,并且这种情况每两步发生一次,“一侧”(第一侧或第二侧)由 half 决定 i.当那一半是 even 时,我们需要使第一个索引不同于 -1,否则第二个索引。
  • 该索引的实际值应为 i/4(整数除法),因为我们可以看到,需要 4 次以上的“迭代”才能使同一索引获得递增一步的值。

实现方法如下:

var max = 2;
var indices = [-1, -1];
var i = 0; // This is the state that determines the 

setInterval(() => {
    index = (i >> 1) % 2;
    if (i % 2 == 0) {  // Every two times, output is -1 -1
        indices[1 - index] = -1;
    } else {
        indices[index] = i >> 2;
    }
    let [firstIndex, secondIndex] = indices;
    console.log(firstIndex, secondIndex);
    i = (i + 1) % ((max + 1) * 4);
}, 300);