javascript - 无法读取未定义的属性 'Push' - Typescript

标签 javascript angular typescript ionic2

当我尝试添加到 Typescript 中的数组(包装在 Ionic2 中)时,我收到一条错误消息,告诉我该数组未定义,即使我已经声明了它。我尝试使用两种不同的声明来声明它,但没有发现问题。我使用的两个声明是:

tracker: any[];

tracker: Array<any>;

我第一次尝试向数组添加任何内容,出现错误的位置如下。我想包含整个函数,以防万一其中有一些东西可以重新定义“this”是什么:

// Answer Correctly
  answerQuestionCorrectly(answer) {
    let answerButton = <HTMLButtonElement>document.getElementById('answer-' + answer.AnswerId);
    answerButton.addEventListener('click', (event) => {
      // Increase the score
      this.currentScore = this.currentScore + this.countdown;
      // Set up quiz review
      var correct = answer.AnswerText;
      var qTrack = {no: this.questionNo, q: this.questionText, a: answer.AnswerText, c: correct}
      console.log(qTrack);
      this.tracker.push(qTrack);
      console.log(this.tracker);
      // Check for end of questions
      if (this.questionNo < this.noOfQuestions) {
        // Remove the old answers
        var parent = document.getElementById('answers');
        this.answers.forEach(element => {
          var button = <HTMLButtonElement>document.getElementById('answer-' + element.AnswerId);
          parent.removeChild(button);
        });
        // Re-init the timer
        this.timer.initTimer();
        // Load Next Question
        this.loadQuestion();
      } else {
        // End the Quiz
        this.endOfQuiz();
      }
    });
  }

最佳答案

这些声明仅指定变量的类型 - 它还需要一个值。尝试类似的事情

var tracker: any[] = [];

将变量初始化为空数组。

关于javascript - 无法读取未定义的属性 'Push' - Typescript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45664859/

相关文章:

angular - 使用 Angular-CLI 安装第 3 方应用程序

Angular 路由器、面包屑组件测试

node.js - 应如何正确处理 Azure Function 中 Azure 服务总线/主题客户端的打开和关闭?

Angular 5 + SignalR (DefinitelyTyped) - 找不到名称 '$'

javascript - 如何在日期为 yyyy-mm-dd 的年份中获得差异?

javascript - ReactJS:如何为sortableJS动态设置禁用选项?

javascript - 随机改变背景图片

javascript - Github 要点 : New Lines?

javascript - Angular 绑定(bind)字符串到单独的行到 html

javascript - 我可以使用 Angular 日期管道格式化没有偏移量的时区吗?