首页 > 解决方案 > 用Javascript在桌子周围传递卡片

问题描述

这似乎是一件愚蠢的简单事情,但我无法弄清楚我做错了什么。目标是拥有一个由 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

标签: javascriptarrays

解决方案


您的代码中有两个错误:

  • if (passer = 0)正在执行任务。你需要if (passer === 0).

  • passer索引正在查看值的错误一侧。目前,您首先从 1 获得并放入 0,然后从 0 获得并放入 7(即 -1)。请注意您如何在第二次迭代中移动相同的值。您需要更改passer = catcher - passDirectionpasser = catcher + passDirection

请注意,使用、 、spliceshiftArray方法(在 main 上)可以更轻松地完成所有这些操作。unshiftpoppushplayerList


推荐阅读