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 trial
Bruno Dias
10,554 PointsPrint an array index and show 1 instead of 0
How can I print an index of an array and display 1 instead of 0 as the first item? Here is what I mean:
var playList = [
[ 'I Did It My Way', 'Frank Sinatra' ],
[ 'Respect', 'Aretha Franklin' ],
[ 'Imagine', 'John Lennon' ],
[ 'Born to Run', 'Bruce S.' ],
[ 'Louie Louie', 'The Kingsmen' ],
[ 'Maybellene', 'Chucky B.' ]
];
function print(message) {
document.write(message);
}
function printSongs(songs) {
var listHTML = '<ul>';
for ( var i = 0; i < songs.length; i++) {
listHTML += '<li>' + i + " " + songs[i][0] + ' by ' + songs[i][1] + '</li>';
}
listHTML += '</ul>';
print(listHTML);
}
printSongs(playList);
This code prints:
0 I Did It My Way by Frank Sinatra
1 Respect by Aretha Franklin
2 Imagine by John Lennon
3 Born to Run by Bruce S.
4 Louie Louie by The Kingsmen
5 Maybellene by Chucky B.
but I wanted to display the index number to start from 1 instead of 0. Is it possible to do that and how can I dot it?
1 Answer
jcorum
71,830 PointsSeveral small changes:
for ( var i = 1; i <= songs.length; i++) {
listHTML += '<li>' + i + " " + songs[i-1][0] + ' by ' + songs[i-1][1] + '</li>';
}
Since the numbers are the loop counter, all you need to do is have it run from 1 to songs.length, instead of from 0 to songs.length - 1 (< songs.length)
You also need to change i to i - 1 in the subscripts.