6

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

1
  • 1
    Is this typescript or javascript? This is not the right way to declare variables in typescript. Commented Jun 14, 2017 at 9:25

2 Answers 2

7

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

6

When you did var ALLcoordinates:number[][];, you did not initialize it with any value. You just specified its type. It will still be undefined at runtime. So undefined[0] throws the error. Initialize it before using it:

var ALLcoordinates: number[][] = [];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.