0

I come from a strong JavaScript background attempting to learn TypeScript. I am encountering a problem that I know would work in JavaScript but is not working in TypeScript:

I am trying to initialize a class member with a matrix or 2d array of 5's; Here is my code:

private rows: number;
private cols: number;
private data: number[][];

constructor(rows: number, cols: number) {
    this.rows = rows;
    this.cols = cols;
    this.data = [];


    // init matrix with fives
    for (let i: number = 0; i < this.rows; i++) {
        this.data[i] = [];
        for (let j: number = 0; j < this.cols; i++) {
            this.data[i][j] = 5; // this is line 21
        }
    }
}

However, whenever I run the code and attempt to create a new instance of this class, I get an error on line 21 (shown above):

Uncaught TypeError: Cannot set property '0' of undefined

I've looked at this for quite a while, and it seems like other people do not have this problem. Does anybody know how to fix this?

Btw: I tried this same code in pure JS, and it worked fine without any errors.

1
  • 3
    Not a Typescript issue, you increment i în the second loop, should be j Commented Jul 18, 2018 at 18:55

2 Answers 2

2

Seems like i is incremented in the second loop too.

for (let i: number = 0; i < this.rows; i++) {
    this.data[i] = [];
    for (let j: number = 0; j < this.cols; j++) { //j here
        this.data[i][j] = 5; // this is line 21
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

I see you are declaring data variable as 2d array then you initialize it as 1d array after constructor. I think in typescript you shouldn't do that.

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.