3 回答

TA貢獻1853條經驗 獲得超9個贊
你不能制作原始值的“淺拷貝” ——當你arr.map(tile => tile[3])制作一個帶有新值的新數組時,所以改變一個不會改變另一個。
但是,您可以創建一個對象數組,因為對象的值是它們的引用
let grid = [
[{value: 1}, {value: 2}],
[{value: 3}, {value: 4}],
];
//take a column
let col2 = grid.map(row => row[1]);
//change one value
col2[1].value = 42;
//the original changed
console.log(grid);
如果需要根據列進行頻繁的更改,則不需要map(row => row[columnNumber])每次都進行甚至矩陣轉置來有效旋轉網格。您可以簡單地制作兩個網格 - 一個代表列,另一個代表行。如果您首先從“普通”網格開始,用對象填充它,然后將其轉置,那么您將有效地對同一數據有兩個視圖:
let rows = [
[ {cell: "a1"}, {cell: "a2"}, {cell: "a3"}, {cell: "a4"} ],
[ {cell: "b1"}, {cell: "b2"}, {cell: "b3"}, {cell: "b4"} ],
[ {cell: "c1"}, {cell: "c2"}, {cell: "c3"}, {cell: "c4"} ],
[ {cell: "d1"}, {cell: "d2"}, {cell: "d3"}, {cell: "d4"} ]
];
//transpose
let columns = rows[0].map((col, i) => rows.map(row => row[i]));
//show
console.log("rows:");
console.log(format(rows));
console.log("----");
console.log("columns:");
console.log(format(columns));
console.log("----");
//take a column
let col2 = columns[1];
//update a value
col2[2].cell = "XX";
//show again
console.log("after the change");
console.log("rows:");
console.log(format(rows));
console.log("----");
console.log("columns:");
console.log(format(columns));
console.log("----");
//helper function to display the grids more compactly
function format(arr) {
return arr
.map(arr => arr.map(({cell}) => cell).join())
.join("\n");
}

TA貢獻1744條經驗 獲得超4個贊
如果你想制作一個淺拷貝,你必須使用一個對象,而不是一個基元。
代碼可能如下所示:
// filling the array:
/*...*/.fill({value: 0})
// changing the value:
myColumn[2].value = 1
我不知道你的應用程序對資源有多敏感,但這樣你的內存消耗會在一定程度上增加(取決于應用程序)。

TA貢獻1815條經驗 獲得超10個贊
// create the original array
let arr = [...Array(4)].map(e => Array(4).fill(0))
console.log(arr)
// get copy of arr with changed column
const cloneSquareAndChangeColumn = (square, colIndex, newValue) => {
return square.map((row, col) => {
return [...row.slice(0, colIndex), newValue, ...row.slice(colIndex + 1)];
});
}
// test changing last column
console.log("cloned and changed arr: \n", cloneSquareAndChangeColumn(arr, 3, 1));
添加回答
舉報