【问题标题】:How to push data into the array [duplicate]如何将数据推送到数组中[重复]
【发布时间】:2018-06-26 19:27:26
【问题描述】:

我正在尝试在按钮单击时推送新标题。我有大约 5 个按钮。每次单击时,我都会将不同的消息推送到数组中。我正在尝试以下代码:

public skills: any[];
public firstMsg: string = 'Press Play to start playing';

onPlay(){
    this.skills.push({ title: this.firstMsg })
}

但现在我收到错误:

ERROR TypeError: Cannot read property 'push' of undefined

我不知道我犯了什么错误。

【问题讨论】:

  • 将数组声明为技能:any[]=[];

标签: angular angular6


【解决方案1】:

初始化数组

public skills: any[] = []

【讨论】:

    【解决方案2】:

    声明时需要赋值空数组

    public skills: any[] = [];
    

    public skills = [];
    

    因为 javascript 不允许对未初始化为数组的变量使用数组属性。

    【讨论】:

      猜你喜欢
      • 2021-09-08
      • 2016-12-23
      • 2021-08-17
      • 1970-01-01
      • 2017-09-19
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 2015-06-20
      相关资源
      最近更新 更多