无法读取未定义属性“推” - Typescript

问题描述:

当我尝试添加到Typescript中的数组(包装在Ionic2中)时,我得到一个错误,告诉我该数组未定义,即使我声明了它。我试过用两个不同的声明来声明它,但没有发现问题。我用了两个声明是:无法读取未定义属性“推” - Typescript

tracker: any[]; 

tracker: Array<any>; 

我第一次尝试任何东西添加到阵列中,并在那里我得到下面的错误是。我想包括整体功能,以防万一有东西在那里,可以重新定义什么“这”是:

// 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[] = []; 

将变量初始化为空数组。

您必须初始化阵列之前,你可以把一个对象进去。

tracker:any [] = [];

你必须这样初始化:

tracker: Array<any>=[];