我有很强的 JavaScript 背景,试图学习 TypeScript。我遇到了一个问题,我知道该问题可以在 JavaScript 中运行,但不能在 TypeScript 中运行:
我正在尝试使用 5 的矩阵或二维数组来初始化类成员;这是我的代码:
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 中尝试了相同的代码,它运行良好,没有任何错误。
最佳答案
似乎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
}
}
关于javascript - Typescript 二维数组定义抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51409112/