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 trialammarkhan
Front End Web Development Techdegree Student 21,661 PointsPrinting a specific number of array
What if, i want to extract only item 3 in array, can i do that while using for loop?
ammarkhan
Front End Web Development Techdegree Student 21,661 PointsJesus Mendoza But, how can i while i am in for loop?
Jesus Mendoza
23,289 PointsIn the video you're using an array called students right?
var students = ['Sascha', 'Lynn', 'Jennifer', 'Paul'];
for (var i = 0; i < 3; i++) {
console.log(students[i]);
}
Note that instead using
i < students.lenght
on the foor loop I used
i < 3
Melissa Austin
3,383 PointsJesus Mendoza Your solution will print out index 0 through 2. The console will log Sascha, Lynn and Jennifer when the goal is to only log Paul. Chris Wiley has the right answer.
Jesus Mendoza
23,289 PointsYea Melissa you're and Chris are right! It seems that I did not understand the question.
2 Answers
Chris Wiley
14,669 PointsThis should do what you want it to:
var listOfItems = ['Item 1', 'Item 2', 'Item 3', 'Item 4'];
for (var i = 0; i < listOfItems.length; i++) {
if ( i === 2 ) {
console.log(students[i]);
}
}
This will print to the console the third item in the list
Jeff Pierce
18,077 PointsTry a conditional; e.g. an if statement...
for (var i = 0; i < students.length; i++){ if (i === 2){ // The third item is index # 2 console.log(students[i]); // This will send the 3rd Student in the array to the console. } }
Jesus Mendoza
23,289 PointsJesus Mendoza
23,289 PointsYeah you can, insead using array.lenght use the number that you want to use