簡體   English   中英

將一維數組轉換為二維數組 JavaScript

[英]Convert 1D array into 2D array JavaScript

嗨,我有這個例子,我希望我的一維數組是一個 4x3 的二維數組

 var array1 = [15, 33, 21, 39, 24, 27, 19, 7, 18, 28, 30, 38]; var i, j, t; var positionarray1 = 0; var array2 = new Array(4); for (t = 0; t < 4; t++) { array2[t] = new Array(3); } for (i = 0; i < 4; i++) { for (j = 0; j < 3; j++) { array2[i][j] = array1[i]; array2[i][j] = array1[j]; } positionarray1 = positionarray1 + 1; //I do this to know which value we are taking } console.log(array2);

我的解決方案只給我 array1 的第一個數字。 任何想法?

i 和 j 是新二維數組的索引,最多只能運行 0 到 3 和 0 到 2,這就是為什么你一遍又一遍地看到開始值的原因。 您需要一種方法來索引從 0 到 11 的 array1。

看起來您在“positionarray1”和“position”的正確軌道上,盡管您需要移動要增加它的位置。 您需要在索引 array1 而不是 i 和 j 時使用該值:

    array2[i][j] = array1[positionarray1];

    array2[i][j] = array1[positionarray1];

    positionarray1++;

如果您將i重命名為row並將j重命名為col ,則更容易看到發生了什么。 另外,避免幻數。 我到處都看到34 這些可以用參數引用替換。 您只需將邏輯包裝在可重復使用的 function 中(如下面的reshape function 所示)。

主要算法是:

result[row][col] = arr[row * cols + col];

無需跟蹤 position,因為可以從當前行和列計算。

 const reshape = (arr, rows, cols) => { const result = new Array(rows); for (let row = 0; row < rows; row++) { result[row] = new Array(cols); } for (let row = 0; row < rows; row++) { for (let col = 0; col < cols; col++) { result[row][col] = arr[row * cols + col]; } } return result; }; const array1 = [15, 33, 21, 39, 24, 27, 19, 7, 18, 28, 30, 38]; const array2 = reshape(array1, 4, 3); console.log(JSON.stringify(array2));
 .as-console-wrapper { top: 0; max-height: 100%;important; }

var array1 = [15, 33, 21, 39, 24, 27, 19, 7, 18, 28, 30, 38];
var i, j, t;
var positionarray1 = 0;
var array2 = new Array(4);

for (t = 0; t < 4; t++) {
  array2[t] = new Array(3);
}

for (i = 0; i < 4; i++) {
  for (j = 0; j < 3; j++) {
    array2[i][j] = array1[i*3+j]; //here was the error
  }

  positionarray1 = positionarray1 + 1; //I do this to know which value we are taking
}

console.log(array2);

我剛剛解決了謝謝你的評論。 我實際上使用了一個分配,但它是 3 而不是 2。

具有 1 個循環以提高效率的解決方案:

 const arr1D = new Array(19).fill(undefined).map((_, i) => i); const arr2D = []; const cols = 3; for (let i = 0, len = arr1D.length; i < len; ++i) { const col = i % cols; const row = Math.floor(i / cols); if (;arr2D[row]) arr2D[row] = []; // create an array if not exist arr2D[row][col] = arr1D[i]. } console,log({ arr1D; arr2D });

暫無
暫無

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

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