arrays - 如何使用 Typescript 定义带有动态键的数组?

标签 arrays angular typescript ionic-framework ionic2

我正在使用位于 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/

相关文章:

javascript - 使用 ngFor 遍历二维数组

arrays - 从数组中随机选择两个不同的项目

java - 将文本文件的 X 和 Y 坐标读取到数组列表中

Docker 容器中.Net Core 托管的 Angular 6 应用程序抛出 Npm 异常

javascript - Typescript 内部模块 - 无法在同一模块中引用导出的类

javascript - Vue 未使用 Axios 请求中的数据从数组更新 Vuetify 数据表

javascript - 如何在 Angular 中构建延迟加载侧边栏?

javascript - Visual Studio javascript 智能感知完全缺失

javascript - 使用javascript按特定顺序对具有十进制值的数组进行排序

angular - 如何在 Angular 6+ CLI 中使用 Handlebars.js?