使用JavaScript将1-D阵列转换为2-D阵列

时间:2013-02-05 13:35:59

标签: javascript

我必须使用JavaScript在控制台中将大约三百个 1x10000 矩阵转换为 100x100矩阵。将每个矩阵拆分为 100x100 矩阵的最有效方法是什么?我假设我需要以某种方式找到,(逗号)的第100个实例,并用], [替换该逗号。我只是在这里学习编程。

var myArray = [2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 7, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 7, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, ... ]

2 个答案:

答案 0 :(得分:0)

使用Array.slice这是一件容易的事:

var myMatrix = Array();
for(i=0; i<100; i++) {
    myMatrix.push(myArray.slice(i*100, (i+1)*100));
}

答案 1 :(得分:0)

var newArray = new Array();
var index= 0;
for (var i=0; i<100; i++)
{ 
    for (var j=0; j<100; j++)
    { 
       newArray[i,j] = myArray[index];
       index++;
    }
}