简体   繁体   English

使用JavaScript将一维数组转换为二维数组

[英]Turning a 1-D Array into a 2-D Array with JavaScript

I have to convert about three hundred 1x10000 matrices into 100x100 matrices in the console with JavaScript. 我必须在使用JavaScript的控制台中将大约三百个1x10000矩阵转换为100x100矩阵 What is the most efficient way to split each matrix into a 100x100 matrix? 将每个矩阵拆分为100x100矩阵的最有效方法是什么? I assume I need to somehow find the 100th instance of a , (comma) and replace that comma with ], [ . 我想我需要以某种方式找到的第100个实例, (逗号),并与替换逗号], [ I am just learning programming here. 我只是在这里学习编程。

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, ... ]

This is an easy thing to do with Array.slice : 使用Array.slice可以很容易地做到这一点:

var myMatrix = Array();
for(i=0; i<100; i++) {
    myMatrix.push(myArray.slice(i*100, (i+1)*100));
}
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++;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM