Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 如何使用Typescript定义具有动态键的数组?_Arrays_Angular_Typescript_Ionic Framework_Ionic2 - Fatal编程技术网

Arrays 如何使用Typescript定义具有动态键的数组?

Arrays 如何使用Typescript定义具有动态键的数组?,arrays,angular,typescript,ionic-framework,ionic2,Arrays,Angular,Typescript,Ionic Framework,Ionic2,我用的是离子2,它位于Angular 2的顶部。我需要创建一个项目数组。我不知道这个数组中会有多少个项目 这是我的打字稿,简化版: import { Component } from '@angular/core'; import { VgAPI } from 'videogular2/core'; @Component({ selector: 'page-class', templateUrl: 'class.html' }) export class ClassPage {

我用的是离子2,它位于Angular 2的顶部。我需要创建一个项目数组。我不知道这个数组中会有多少个项目

这是我的打字稿,简化版:

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
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]
在任何地方都没有明确定义。但这是一个问题,因为我不知道有多少项目将在哪里。如何正确定义此数组以允许此行为?

这是因为
api
未定义的
,您必须将其设置为空数组:

@Component({
  selector: 'page-class',
  templateUrl: 'class.html'
})
export class ClassPage {
  // initialize as empty array
  public api: VgAPI[] = [];

  constructor(...){}

  // Load API when videos are ready
  onPlayerReady(api: VgAPI, i: number) {
    this.api[i] = api;
  }
}
因此,在初始化过程中不需要提供大小

JavaScript数组的长度和元素的类型都不是固定的

你还没有初始化数组,所以你只需要这样做,没有大小

i、 e

api:any[]应该是
api:any[]=[]

这里有一个小清理工作

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);

您需要在构造函数中将变量设置为空数组:this.api=[];数组没有“键”,它们有“索引”。根据定义,所有数组都是动态的。我想知道为什么有人否决了这个答案。看不出有什么问题。可能是因为OP的问题相当于打字错误。他收到一个错误,说
无法设置未定义的
的属性“1”。因此,
this.api
显然是未定义的。这并不奇怪,
this.api
是未定义的,因为它从未初始化过<代码>api
是在构造函数中定义的-我知道
api[1]
没有定义(我在我的问题中提到了这一点),我知道这就是为什么我会得到错误,问题是为什么在构造函数中设置为
any
时会出现这种情况。这个答案回答了这个问题。你的评论毫无帮助,缺乏建设性,而且是错误的;没有输入错误,我只是不知道我必须初始化为数组。@mikemike,嗯,意识到如果你不初始化某个东西,那么它就没有初始化似乎没有那么复杂。“定义”不是“初始化”。指定类型不会初始化。错误为
undefined
。我正在定义它。在询问之后,我似乎也需要初始化。我不确定你的问题是什么。。。