当我尝试添加到 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/