简体   繁体   中英

Converting One Dimensional Array to Two Dimensional

I have a one dimensional array which I want to convert to two dimensional array. So, I use loop for that. To prove that every index array has been correctly entered, I print it to the screen. But it only prints the first row and after that it throws an error

Uncaught TypeError: Cannot set property '0' of undefined

I heard that in JS the array is somewhat different compared to other languages (I'm most familiar with Java). So, maybe I have confused it somehow, but I have no idea.

Here's my code.

 var k = 0; //move tha matrix from one dimensional matrix to two dimensional var cubes = new Array([]); for(var i = 0; i < n; i++){ for(var j = 0; j <= n; j++){ cubes[i][j]=matriks[k]; document.write("["+ i +"]["+ j +"] = "+cubes[i][j].value + " "); k++; } } 

The matrix is a one dimensional array. And the cubes is the two dimensional array which I want to place the matrix into.

The problem is that you do not tell JavaScript that the Objects stored in the outer-most array should be an Array. When you tried to use the inner arrays, you had not yet initialized them, so you were getting undefined. To fix this, you can simply change your code to:

var k=0; 
var cubes = [];
var i, j;
for(i=0; i<n; i++){
    cubes[i] = [];
    for(j=0; j<=n; j++){
        cubes[i][j]=matriks[k];
        document.write("["+i+"]["+j+"] = "+cubes[i][j].value+" ");
        k++;
    }
    j=0;
}

the declaration of the bidimensional array "cubes" is not correct as you do, you have to initialize each row of your matrix, this generate the error

var k=0;
//move tha matrix from one dimensional matrix to two dimensional
var cubes = [];
for(var i=0; i<n; i++){
    cubes[i] = [];
    for(var j =0; j<=n; j++){
        cubes[i][j]=matriks[k];
        console.log("value at ", i, j, " = ", cubes[i][j]);
        k++;
    }
}

This line:

var cubes = new Array([]);

creates an array with one entry in it, which is another array. It does not create a multi-dimensional array (JavaScript doesn't have them, it has arrays of arrays). This means that there is no array anywhere in cubes except at entry [0] .

To fix it, change that to

var cubes = [];

and add

cubes[i] = [];

just after

for(var i=0; i<n; i++){

to create each subarray.

Eg:

var k=0;
//move tha matrix from one dimensional matrix to two dimensional
var cubes = [];
for(var i=0; i<n; i++){
    cubes[i] = [];
    for(var j =0; j<=n; j++){
        cubes[i][j]=matriks[k];
        document.write("["+i+"]["+j+"] = "+cubes[i][j].value+" ");
        k++;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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