Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript - initialize a 2D array ERROR

I'm trying to create a 2D array for coordinates like [[x_1,y_1,z_1], [x_2,y_2,z_2], [...],...].

Here is my code for initialization and initial declaration:

var ALLcoordinates:number[][];

for (var i=0; i< dims; i++) {
    ALLcoordinates[i]=[];
    for (var j=0; j<chainSize; j++){
        ALLcoordinates[i][j]=0;
    }
}

After that, I assign new values for each row in this loop :

for (var i = 0; i < chainSize; i++) {
    var alea1 = Math.floor(Math.random()*(3-0+1))+0;
    var alea2 = Math.floor(Math.random()*(3-0+1))+0;
    var alea3 = Math.floor(Math.random()*(3-0+1))+0;
    var coordinates:number[];
    coordinates = [alea1,alea2,alea3];
    ALLcoordinates[i]=coordinates;

}

But when I compile it, I get this error Uncaught TypeError: Cannot set property '0' of undefined for this line ALLcoordinates[i] = [];

I would appreciate any help, thanks

like image 308
Oxana Ushakova Avatar asked Jun 14 '17 09:06

Oxana Ushakova


People also ask

How to initialize a 2d array in TypeScript?

To declare a two-dimensional array, set the type of the array as Type[][] , e.g. const arr: string[][] = [['one'], ['two']] . You can read the type as an array containing arrays of specific type. Trying to add any other type to the array would cause the type checker to error out.

How to use multidimensional array in TypeScript?

Master Typescript : Learn Typescript from scratchAn array element can reference another array for its value. Such arrays are called as multidimensional arrays. TypeScript supports the concept of multi-dimensional arrays. The simplest form of a multi-dimensional array is a two-dimensional array.

How do you make a multidimensional array?

You can create a multidimensional array by creating a 2-D matrix first, and then extending it. For example, first define a 3-by-3 matrix as the first page in a 3-D array. Now add a second page. To do this, assign another 3-by-3 matrix to the index value 2 in the third dimension.

How do you define an array of objects in TypeScript?

To declare an array of objects in TypeScript, set the type of the variable to {}[] , e.g. const arr: { name: string; age: number }[] = [] . Once the type is set, the array can only contain objects that conform to the specified type, otherwise the type checker throws an error. Copied!


1 Answers

Declaring an array does not initialize it.

You are missing the ALLcoordinates initialization:

var ALLcoordinates:number[][];

ALLcoordinates = [];            //  ◄ initialize the array

for (var i=0; i< dims; i++) {
    ALLcoordinates[i]=[];
    for (var j=0; j<chainSize; j++){
        ALLcoordinates[i][j]=0;
    }
}
like image 200
Koby Douek Avatar answered Sep 19 '22 14:09

Koby Douek