Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialRobert Tyree
13,335 PointsArray returning "undefined" after push method
Hi there. I'm trying to understand why the push-method approach used in the Treetunes model doesn't seem to be functioning in the JavaScript below. Any idea why the final alert there would return undefined rather than with the question object?
Thanks a bunch for any tips!
//quiz.js
function Quiz() {
this.questions = [];
this.currentQuestionIndex = 0;
}
Quiz.prototype.add = function(question) {
this.questions.push(question);
};
//question.js
function Question(question, choice0, choice1, answer) {
this.question = question;
this.choice0 = choice0;
this.choice1 = choice1;
this.answer = answer;
}
//app.js
var quiz = new Quiz();
var questionA = new Question("Where are you?", "Portland", "France", "France");
var questionB = new Question("Who are you?", "Joe", "Robert", "Robert");
quiz.add(questionA);
quiz.add(questionB);
alert(quiz[0].choice0);
//Not sure why this won't load! Why is the array position returning undefined?
The scripts are loaded in this order in the HTML file.
<script src="quiz.js"></script>
<script src="question.js"></script>
<script src="quiz_ui.js"></script>
<script src="app.js"></script>
1 Answer
Steven Parker
231,269 PointsYour Quiz object is not an array, and has no property named "choice0".
Were you intending to access the first stored Question object instead? Perhaps you meant to write this:
alert(quiz.questions[0].choice0);
Robert Tyree
13,335 PointsRobert Tyree
13,335 PointsThanks Steven! You nailed it.