javascript - 用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("...");
}
解决方案
您的代码中有两个错误:
if (passer = 0)
正在执行任务。你需要if (passer === 0)
.passer
索引正在查看值的错误一侧。目前,您首先从 1 获得并放入 0,然后从 0 获得并放入 7(即 -1)。请注意您如何在第二次迭代中移动相同的值。您需要更改passer = catcher - passDirection
为passer = catcher + passDirection
请注意,使用、 、splice
和shift
Array方法(在 main 上)可以更轻松地完成所有这些操作。unshift
pop
push
playerList
推荐阅读
- javascript - JavaScript 在标签中显示表格中下拉列表的每个选定值
- python - 如何在 python 3.6 中按不同类拆分数据
- mysql - 如何显示包含特定值的多个表中的行
- c# - FluentValidations 从 RuleBuilderOptions 获取 Propertyname
- python - Alexa python lambda_handler 未创建事件会话
- bash - 使用 ls 命令时如何在文件夹名称中添加字符?
- oracle-apex-5.1 - Oracle APEX - 如何将经典报表行标记为选中
- vhdl - 在 VHDL 中使用 SB_RGBA_DRV 原语
- spring - 使用 FlatFileItemWriter 将数据写入 InputStream
- c# - 如何从遇到错误但需要类型的方法返回