卡片在Java表格中的传递手

问题描述 投票:0回答:2

这似乎很简单,但是我无法弄清楚自己在做什么错。目标是拥有一个由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

javascript arrays
2个回答
1
投票

您的代码中有两个错误:

  • if (passer = 0)正在执行分配。您需要if (passer === 0)

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

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


0
投票

您可以通过使用Array方法将元素从数组的开头移至结尾(反之亦然)来简化生活。在for循环的主体中使用它应该可以解决问题:

if (passDirection === -1) {
    const first = playerList.shift();
    playerList.push(first);
}
else {
    const last = playerList.pop();
    playerList.unshift(last);
}
© www.soinside.com 2019 - 2024. All rights reserved.