2017-08-13 45 views
2

當我嘗試添加到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(); 
     } 
    }); 
    } 

回答

2

這些聲明只指定類型的變量 - 它也需要一個值。嘗試類似

var tracker: any[] = []; 

將變量初始化爲空數組。

1

您必須初始化陣列之前,你可以把一個對象進去。

tracker:any [] = [];

1

你必須這樣初始化:

tracker: Array<any>=[]; 
相關問題