Anna RG - 3 months ago 15

Javascript Question

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.

Answer

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;
}
```

Source (Stackoverflow)

Comments