首页 > 解决方案 > 如何在 TypeScript 中创建矩形列表?

问题描述

如何声明矩形类型列表?

我在没有列表的情况下尝试过这种方式,但没有奏效:

在 TypeScript 文件中:

var i = 0;
var j = 0;
var index = 0;
class Rectangles {
    x: number;
    y: number;
    height: number;
    width: number;
}
let rects: Array<Rectangles>;
function Load()
{
    for (i = 0; i < 5; i++) {
        for (j = 0; j < 10; j++) {
            rects[index].x = 25 + (j * 25);
            rects[index].y = 25 + (i * 25);
            rects[index].width = 25;
            rects[index].height = 25;
            index++;
        }
    }

}

function myClick() {
    var canvas = <HTMLCanvasElement>document.getElementById("canvas");
    let context: CanvasRenderingContext2D = canvas.getContext("2d");
    i = 0;
    j = 0;
    index = 0;
    for (i = 0; i < 5; i++)
    {
        for (j = 0; j < 10; j++)
        {
            context.beginPath();
            context.rect(rects[index].x, rects[index].y, rects[index].width, rects[index].height);
            context.fillStyle = "White";
            context.fill();
            context.lineWidth = 2;
            context.strokeStyle = "Black";
            context.stroke();
            index++;
        }
    } 
}

我在 HTML 页面中调用了该函数。

所以我需要知道如何声明为一个列表。

在 c# 中,我们将这样做:

List<Rectangle> rects = new List<Rectangle>();

我怎样才能在 TypeScript 中做到这一点?

标签: htmltypescript

解决方案


function Load()
 {
  for (i = 0; i < 5; i++) {
    for (j = 0; j < 10; j++) {
       let rect = new Rectangle();
        rect.x = 25 + (j * 25);
        rect.y = 25 + (i * 25);
        rect.width = 25;
        rect.height = 25;
        rects[index++;] = rect;
    }
    }
  }

您在创建矩形数组方面几乎是正确的。将此数组想象成容器,并且要填充容器,您需要矩形类型。所以你必须先创建矩形,然后添加到容器中,在这种情况下是矩形。在此之前,您需要先初始化容器,如 rects = []。


推荐阅读