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 trialVic Mercier
3,276 PointsProblem...
1.I'd like to make a little quizz game but instead of t the question are already there(in the 2 dimensional array)I want to capture by a prompt dialog then add them to my two dimensinal array. var question = [ [], [] ]; var lol; for(var i = 0; i < question.length; i += 1){ lol = prompt("Please type a question"); question[i][0].push(lol); }
The promblem is that the loop cannnot run more than one time.It just run once and the queston.length is 2 so the loop should run two times because i was set to zero.
Victor
Thank you for your help!
2 Answers
andren
28,558 PointsIt technically does not even loop once, it stops once it encounters this line:
question[i][0].push(lol);
If you look at the console after running that command you will see this:
TypeError: Cannot read property 'push' of undefined
The issue is the [0]
part of that line, it does not belong there. The [i]
tells JavaScript to retrive the i
element of the array, which at first will be the first nested array. Then the [0]
tells it to retrieve the first element of that array, which does not exist since the nested array is empty. Hence the error.
The push
method should be called directly on the nested array, so by removing the [0]
like this:
var question = [ [], [] ];
var lol;
for(var i = 0; i < question.length; i += 1){
lol = prompt("Please type a question");
question[i].push(lol);
}
console.log(question)
Your code will function in the way I'm guessing you intended it to.
Vic Mercier
3,276 PointsBut could do we add an element in a precise place in a two dimensional Arras?
Brennan Altringer
7,660 PointsYou can add a value to a 2D array in a specific spot. But in your loop 0 is static so I'm not sure you need a 2D array. You could use a singular array and achieve the same results based on your code above.
if you wanted a 2d array you would need a nested for loop like so:
var question = [ [], [] ];
var lol;
for(var i = 0; i < question.length; i ++){
for(var j = 0; j < question.length; j ++){
lol = prompt("Please type a question");
question[i][j].push(lol);
}
}
console.log(question)
If that what you are looking for?