簡體   English   中英

如何在TypeScript中初始化(聲明)數組?

[英]How to initialize (declare) an array in TypeScript?

我絕對是TypeScript的初學者。 我想通過“for”循環在TypeScript中初始化一個數字數組,如下所示:

 public hours: number[];
 constructor() {
   for (let i: number = 1; i < 25; i++) {
      this.hours[i] = i;
    }
  }

我收到一個錯誤:無法設置未定義的屬性“1”。 請你幫助我好嗎?

這一行:

public hours: number[];

不創建新數組,它只聲明它。
如果您編譯此代碼:

class MyClass {
    public hours: number[];

    constructor() {
        for (let i: number = 1; i < 25; i++) {
            this.hours[i] = i;
        }
    }
}

你得到:

var MyClass = (function () {
    function MyClass() {
        for (var i = 1; i < 25; i++) {
            this.hours[i] = i;
        }
    }
    return MyClass;
}());

如您所見, this.hours未被分配。

所以你需要這樣做:

constructor() {
    this.hours = [];

    for (let i: number = 1; i < 25; i++) {
        this.hours[i] = i;
    }
}

要么:

public hours: number[] = [];

小時未設置為任何值。 您可以在構造函數中創建新數組,或將小時設置為空數組:

public hours: number[] = [];
constructor() {
   for (let i: number = 1; i < 25; i++) {
      this.hours[i] = i;
   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM