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
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.
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.
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.
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!
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With