将1D数组转换为2D数组

Shw*_*pta 16 javascript arrays

我正在开发一个程序,我必须将文本文件中的值读入一维数组.我已成功获取该1D数组中的数字.

m1=[1,2,3,4,5,6,7,8,9]
Run Code Online (Sandbox Code Playgroud)

但我想要阵列

m1=[[1,2,3],[4,5,6],[7,8,9]]
Run Code Online (Sandbox Code Playgroud)

Kar*_*non 39

您可以使用此代码:

var arr = [1,2,3,4,5,6,7,8,9]

var newArr = [];
while(arr.length) newArr.push(arr.splice(0,3));

console.log(newArr)
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/JbL3p/


Mr.*_*irl 5

Array.prototype.reshape = function(rows, cols) {
  var copy = this.slice(0); // Copy all elements.
  this.length = 0; // Clear out existing array.

  for (var r = 0; r < rows; r++) {
    var row = [];
    for (var c = 0; c < cols; c++) {
      var i = r * cols + c;
      if (i < copy.length) {
        row.push(copy[i]);
      }
    }
    this.push(row);
  }
};

m1 = [1, 2, 3, 4, 5, 6, 7, 8, 9];

m1.reshape(3, 3); // Reshape array in-place.

console.log(m1);
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { top:0; max-height:100% !important; }
Run Code Online (Sandbox Code Playgroud)

输出:

[
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
]
Run Code Online (Sandbox Code Playgroud)

JSFiddle DEMO