我正在使用Ionic 2,它位於Angular 2之上。我需要創建一個項目數組。我不知道該陣列中有多少物品。如何使用Typescript使用動態鍵定義數組?
這裏是我的打字稿,簡化:
import { Component } from '@angular/core';
import { VgAPI } from 'videogular2/core';
@Component({
selector: 'page-class',
templateUrl: 'class.html'
})
export class ClassPage {
api: any[];
constructor(...){}
// Load API when videos are ready
onPlayerReady(api: VgAPI, i: any) {
this.api[i] = api;
}
}
onPlayerReady
時調用視頻播放器在我看來intialize。 i
是該玩家的ID(0,1,2,...)。
我預計這個構建的數組:
this.api[0] = VgAPI (of player 1)
this.api[1] = VgAPI (of player 2)
this.api[2] = VgAPI (of player 3)
this.api[3] = VgAPI (of player 4)
this.api[4] = VgAPI (of player 5)
不幸的是,我得到如下:
Runtime Error
Cannot set property '1' of undefined
我相信這是因爲this.api[0]
沒有明確定義的任何地方。但是,這是一個問題,因爲我不知道將會有多少物品。我如何正確定義這個數組來允許這種行爲?
您需要在構造函數中將您的變量設置爲空數組:this.api = []; –
數組沒有「鍵」,它們有「索引」。根據定義,所有陣列都是動態的。 – 2017-07-25 12:46:02