打字稿二维数组定义引发错误

时间:2018-07-18 18:52:17

标签: javascript typescript

我来自具有深厚JavaScript背景的尝试学习TypeScript的人。我遇到一个我知道可以在JavaScript中工作但不能在TypeScript中工作的问题:

我正在尝试使用5的矩阵或2d数组初始化类成员;这是我的代码:

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
        }
    }
}

但是,每当我运行代码并尝试创建此类的新实例时,在第21行(如上所示)都会出现错误:

Uncaught TypeError: Cannot set property '0' of undefined

我已经看了很长时间了,看来其他人没有这个问题。有人知道如何解决这个问题吗?

顺便说一句:我在纯JS中尝试了相同的代码,并且工作正常,没有任何错误。

2 个答案:

答案 0 :(得分:2)

好像 i 在第二个循环中也增加了。

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
    }
}

答案 1 :(得分:0)

我看到您将数据变量声明为2d数组,然后在构造函数之后将其初始化为1d数组。我认为在打字稿中您不应该这样做。

相关问题