这似乎是一件愚蠢的简单事情,但我无法弄清楚自己在做什么错。目标是拥有一个由8个其他数组组成的数组,每个数组包含手牌(在示例中,这些数组仅包含任意数字)。然后,根据passDirection是设置为-1还是1,将循环遍历每个数组,并用其旁边的数组替换。理想的最终结果是playerList的值实际上向上或向下移动1,并且可以重复多次而不会出现问题。

我下面的代码实际上发生的是,除了第一个数组外,所有数组都只是被索引为0的数组所替换。我怎样才能解决这个问题?

var playerList = new Array;
var passDirection = -1;

for(i = 0; i < 8; i++) {
  playerList.push([playerList.length,i]); // Fill Arrays with arbitrary data
}

for (i=0; i< playerList.length; i++) {
  console.log(i + ": " + playerList[i]); // Check their values before anything is done to them
}

for(q=0; q < 5; q++){ // Repeat the process 5 times, just because.

  var bufferArray = playerList[0]; // Put Array Element 0's value in a buffer as it will be replaced first

  for(i = 0; i < playerList.length && i > (playerList.length * -1); i += passDirection) {
      var catcher = i; // 'catcher' should be the array that gets replaced
      var passer = catcher - passDirection; // 'passer' should be the one it gets replaced with
      if (catcher < 0) {
          catcher = catcher + playerList.length;
      }
      if (passer < 0) {
          passer = passer + playerList.length;
      } else if (passer >= playerList.length) {
          passer = passer - playerList.length;
      }

      if (passer == 0) {
          playerList[catcher] = bufferArray;

      } else {
          playerList[catcher] = playerList[passer];
      }
  }

  for (i=0; i< playerList.length; i++) {
    console.log(i + ": " + playerList[i]);
  }
  console.log("...");
}


https://jsfiddle.net/3r1Lhwc5

最佳答案

您的代码中有两个错误:


if (passer = 0)正在执行分配。您需要if (passer === 0)
passer索引看值的反面。目前,您首先是从1开始并进入0,然后从0开始并进入7(即-1)。注意在第二次迭代中如何移动相同的值。您需要将passer = catcher - passDirection更改为passer = catcher + passDirection


请注意,使用spliceshiftunshiftpoppush数组方法(在主playerList上)可以轻松完成所有这些操作。

10-06 04:22