简体   繁体   English

无法读取未定义的属性“推”-打字稿

[英]Cannot Read Property 'Push' of undefined - Typescript

When I try to add to an array in Typescript (wrapped in Ionic2) I get an error telling me the array is undefined even though I've declared it. 当我尝试添加到Typescript中的数组(包装在Ionic2中)时,我收到一条错误消息,即使我已声明该数组未定义。 I've tried declaring it using two different declarations and not found the problem. 我尝试使用两个不同的声明来声明它,但未发现问题。 The two declarations I used are: 我使用的两个声明是:

tracker: any[];

and

tracker: Array<any>;

The first time I try to add anything to the array and where I get the error is below. 我第一次尝试将任何东西添加到数组中,然后从哪里得到错误,如下所示。 I wanted to include the whole function, just in case there was something in there that could be redefining what 'this' is: 我想包括整个函数,以防万一其中有些东西可以重新定义“ 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();
      }
    });
  }

Those declarations only specify the type of the variable — it also needs a value. 这些声明仅指定变量的类型 ,它也需要一个值。 Try something like 尝试类似

var tracker: any[] = [];

to initialise the variable to an empty array. 将变量初始化为一个空数组。

You have to initialize the array before you can push an object into it. 您必须先初始化数组,然后才能将对象推入其中。

tracker: any[ ] = [ ]; 跟踪器:any [] = [];

您必须像这样初始化它:

tracker: Array<any>=[];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM