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.