【问题标题】:Cannot Read Property 'Push' of undefined - Typescript无法读取未定义的属性“推送”-Typescript
【发布时间】:2018-01-21 17:19:49
【问题描述】:

当我尝试在 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();
      }
    });
  }

【问题讨论】:

    标签: javascript angular typescript ionic2


    【解决方案1】:

    您必须先初始化数组,然后才能将对象推入其中。

    跟踪器:任何[] = [];

    【讨论】:

      【解决方案2】:

      那些声明只指定变量的类型——它还需要一个值。尝试类似

      var tracker: any[] = [];
      

      将变量初始化为一个空数组。

      【讨论】:

        【解决方案3】:

        你必须像这样初始化它:

        tracker: Array<any>=[];
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-06-11
          • 2019-02-02
          • 2021-03-06
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多