javascript - Typescript 二维数组定义抛出错误

标签 javascript typescript

我有很强的 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/

相关文章:

javascript - javascript 中的 "this"在 Internet Explorer 中的行为不同

javascript - Cookie 在 Web 应用程序中的用途是什么?

javascript - Angular 中 tsconfig.json 文件的 lib 数组中的 dom 是什么?

typescript - 我可以使用部分实体通过 typeorm 进行保存吗?

javascript - php javascript 刷新页面

javascript - 更改数据属性后如何刷新 DOM

javascript - 使用 Ordnance Survey/Openlayers api 拖动标记

Angular 2 降级组件 : Why the constructor params bring this error: (SystemJS) Can't resolve all parameters for (? )

javascript - 创建后在带有模型的 html 页面中显示值

javascript - 按向下或向上箭头键仅突出显示过滤的项目