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 trialolu adesina
23,007 Pointscan i use a for in loop within a for loop
{name:'Olu Adesina',
track:'javaScript',
achievements:'loops,objects',
points:1568},
{name:'Olu Adesina',
track:'javaScript',
achievements:'loops,objects',
points:1568},
{name:'Olu Adesina',
track:'html',
achievements:'loops,objects',
points:1568},
{name:'Olu Adesina',
track:'javaScript',
achievements:'loops,objects',
points:1568},
{name:'jack Adesina',
track:'javaScript',
achievements:'loops,objects',
points:1568},
]
var message;
for(x=0;x<students.length;x+=1){
for(var name in[x]){
message+= name, ':',[x][name]
}
}
document.write(message)
2 Answers
Steven Parker
229,744 PointsSure you can.
But I don't think your inner loop is properly formed. And if I understand what you're intending to do here, you probably meant to write something like this:
for (x = 0; x < students.length; x += 1) {
for (var name in students[x]) {
message += name + ": " + students[x][name] + "<br>";
}
message += "<br>";
}
Also, since you want to append to it, when you declare message you should initialize it with an empty string.
evannex
2,436 PointsThe simple answer is yes you can definitely use a for loop inside another for loop. However, in your code above, the inner for loop is not structured correctly. In this case I believe the inner for could be swapped for an if statement to achieve the desired functionality.