我正在使用位于 Angular 2 之上的 Ionic 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
在我 View 中的视频播放器初始化时调用。 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]
没有在任何地方明确定义。但这是一个问题,因为我不知道会有多少项目。我怎样才能正确定义这个数组以允许这种行为?
最佳答案
Arrays in JavaScript are naturally dynamic in length因此您无需在初始化期间提供大小。
Neither the length of a JavaScript array nor the types of its elements are fixed.
你还没有初始化数组,所以你只需要这样做,没有大小。
即
api: any[];
应该是 api: any[] = [];
这是一个有效的 JSFiddle稍微清理一下。
interface VgAPI {
name: string;
}
class ClassPage {
private api: VgAPI[] = [];
public onPlayerReady = (api: VgAPI, index: number) => {
this.api[index] = api;
};
}
let classPage = new ClassPage();
classPage.onPlayerReady({ name: "foo" }, 1);
关于arrays - 如何使用 Typescript 定义带有动态键的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45301896/