亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用類似函數的映射創建數組的淺表副本?

如何使用類似函數的映射創建數組的淺表副本?

斯蒂芬大帝 2021-06-28 12:51:40
如果我有一個 4x4 2d 數組并且想要處理特定列,我可以使用地圖獲取它并將其設置回來,或者我可以獲得它的淺表副本并直接處理原始數組值。獲取/設置方式// create the original arraylet arr = [...Array(4)].map(e => Array(4).fill(0))console.log(arr)// get a specific column, e.g. the 3dlet myColumn = arr.map(tile => tile[3])// change itmyColumn[2] = 1// set it backarr.map((line, i) => line[3] = myColumn[i])console.log("modified array", arr)現在,我怎樣才能用淺拷貝實現同樣的事情,即不必重新設置值?
查看完整描述

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");

}


查看完整回答
反對 回復 2021-07-08
?
慕無忌1623718

TA貢獻1744條經驗 獲得超4個贊

如果你想制作一個淺拷貝,你必須使用一個對象,而不是一個基元。


代碼可能如下所示:


// filling the array:

/*...*/.fill({value: 0})

// changing the value:

myColumn[2].value = 1

我不知道你的應用程序對資源有多敏感,但這樣你的內存消耗會在一定程度上增加(取決于應用程序)。


查看完整回答
反對 回復 2021-07-08
?
動漫人物

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));


查看完整回答
反對 回復 2021-07-08
  • 3 回答
  • 0 關注
  • 171 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號