【问题标题】:How to change position in array using array-move method?如何使用数组移动方法更改数组中的位置?
【发布时间】:2019-11-28 16:04:46
【问题描述】:

我的目的是创建 PuzzleGame,例如 http://migo.sixbit.org/puzzles/fifteen/

主要优先事项是将 Cells 从具有 value 的一个移动到另一个 undefined

这是我的功能:

  moveCell(row, col) {
    this.puzzleTable = [];
    let actRow = 0,
      actCol = 0;

    for (let r = -1; r <= 1; r++) {
      actRow = row + r;
      if (actRow >= 0 && actRow < this.rowCount) {

        moveCells(this.puzzleTable[actRow][col], row, actRow);
      }
    }
    for (let c = -1; c <= 1; c++) {
      actCol = col + c;
      if (actCol >= 0 && actCol < this.colCount) {

        moveCells(this.puzzleTable[row][actCol], col, actCol);

      }
    }
  }

例如:

Arr[0][0] to Arr[1][1]

我不想改变他们的价值,我希望他们交换

最佳做法是什么?

【问题讨论】:

标签: javascript arrays logic


【解决方案1】:

您可以简单地将两个单元格的值存储在两个临时变量中,并相应地分配它们。

例如:

var tempA=Arr[0][0];
var tempB=Arr[1][1];
Arr[0][0]=tempB;
Arr[1][1]=tempA;

【讨论】:

    【解决方案2】:

    How to swap two elements inside of a 2D Array in JavaScript? (Confused about what I’m seeing from console.log in Chrome) 上的这种交换看起来更容易

    var points = [[1, 2], [10, 20], [100, 200]];
    console.log(points.toString());
    [points[1], points[2]] = [points[2], points[1]];
    var points = [[1, 2], [10, 20], [100, 200]];
    console.log(points.toString());
    [points[1], points[2]] = [points[2], points[1]];
    console.log(points.toString());
    

    【讨论】:

    • 如果问题已经在 SO 中的某个地方找到了答案,则不要在此处复制/粘贴它,而是将其标记为重复
    猜你喜欢
    • 1970-01-01
    • 2012-10-24
    • 2022-01-08
    • 2018-08-29
    • 1970-01-01
    • 1970-01-01
    • 2018-03-13
    • 2019-07-07
    • 1970-01-01
    相关资源
    最近更新 更多