[英]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.