簡體   English   中英

如何在其他 arrays 之間移動二維數組中的元素? Javascript

[英]How to move an element in 2D array between other arrays ? Javascript

數組示例:

let arr = [
  [1, 1, 1, 1],
  [2, 2, 2, 2],
  [3, 3, 3, 0],
];

我希望能夠將“0”向左向右向上向下移動

例如向上移動“0”元素:

[
  [1, 1, 1, 1],
  [2, 2, 2, 0], //<---
  [3, 3, 3, 2],
];

我已經能夠使用 function 左右移動元素,如下所示:

function changePosition(arr, from, to) {
  arr.splice(to, 0, arr.splice(from, 1)[0]);
  return arr;
}

我想知道如何向上和向下移動元素。 我將不勝感激,因為我在 inte.net 上沒有找到太多代碼。

你可以這樣做

 let arr = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 0], ]; const findPos = () => { const y = arr.findIndex(a => a.includes(0)) return [arr[y].indexOf(0), y] } const up = () => { const [x, y] = findPos() if (y <= 0) { return; } let temp = arr[y - 1][x] arr[y - 1][x] = 0 arr[y][x] = temp } const down = () => { const [x, y] = findPos() if (y >= arr.length - 1) { return; } let temp = arr[y + 1][x] arr[y + 1][x] = 0 arr[y][x] = temp } const left = () => { const [x, y] = findPos() if (x <= 0) { return; } let temp = arr[y][x -1] arr[y][x - 1] = 0 arr[y][x] = temp } const right = () => { const [x, y] = findPos() if (x >= arr[y].length - 1) { return; } let temp = arr[y][x + 1] arr[y][x + 1] = 0 arr[y][x] = temp } console.log(arr, findPos()) up() console.log(arr, findPos()) left() console.log(arr, findPos()) down() console.log(arr, findPos())

您可以嘗試將值交換為您喜歡的任何索引。

     function swap(yourArray,topOrBottomArray,positionOfYourNum){   
     //positionOfYourNum is 3 in your case
     let temp = yourArray[positionOfYourNum];
     yourArray[positionOfYourNum] = topOrBottomArray[positionOfYourNum];
     topOrBottomArray[positionOfYourNum] = temp;
     }

然后打電話

     swap(arr[2],arr[1],3);  //3 is the index of 0
     console.log(arr);

Result = [
  [1, 1, 1, 1],
  [2, 2, 2, 0], 
  [3, 3, 3, 2],
];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM