簡體   English   中英

如何在Javascript中使用對象作為默認值創建多維數組?

[英]How to create a multidimensional array with an object as default value in Javascript?

我想創建多維數組時遇到麻煩。

我不知道為什么,但是當我想創建一個以對象作為默認值的多維數組時,我得到一個奇怪的行為。

我使用了不同的方式,例如:

當我想更改對象字段的任何一個時,都會出現問題。

 function matrix( rows, cols, defaultValue){ var arr = []; // Creates all lines: for(var i=0; i < rows; i++){ // Creates an empty line arr.push([]); // Adds cols to the empty line: arr[i].push( new Array(cols)); for(var j=0; j < cols; j++){ // Initializes: arr[i][j] = defaultValue; } } return arr; } var myArray = matrix(5, 5, { status: 'OK' }); myArray[2][1].status = 'NOT OK'; console.log('Strange behavior', myArray); 

更改擴展到其他位置。

有誰能夠幫助我?

因為您一遍又一遍地存儲對一個相同對象的引用,所以您具有所描述的行為。 要獲取單獨的對象,可以在每次需要時使用object.assign來創建defaultValue的(淺)副本:

arr[i][j] = Object.assign({}, defaultValue);

使用其他一些ES6功能,您的代碼可能如下所示:

 function matrix( rows, cols, defaultValue){ return Array.from(Array(rows), row => Array.from(Array(cols), cell => Object.assign({}, defaultValue)) ); } var myArray = matrix(5, 5, { status: 'OK' }); myArray[2][1].status = 'NOT OK'; console.log('Correct behavior', myArray); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

問題是您要在矩陣的每個點分配相同的對象。 因此,如果在數組的某一點更改對象,則在所有其他點也將更改。 要解決此問題,請使用克隆函數(例如下划線或jQuery的)或為矩陣中的每個點實例化一個新對象。

代替

arr.push([]);
// Adds cols to the empty line:
arr[i].push( new Array(cols));

嘗試

arr.push( new Array(cols));

對象通過它們的引用傳遞,因此您要為矩陣中的所有單元格分配對同一對象的引用,從而使它們成為同一對象(更改一個對象也會導致其他對象也發生更改)。 您必須復制對象。 如果您正在使用最新的ECMAScript,則可以使用Object.assign如下所示:

function matrix( rows, cols, defaultValue) {
  var arr = [];
  for(var i=0; i < rows; i++) {
      var row = [];  // create a row
      arr.push(row); // push it into the matrix

      for(var j=0; j < cols; j++) {
        row[j] = Object.assign({}, defaultValue); // copy the default value and assign it to this cell
      }
  }
    return arr;
}

暫無
暫無

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

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