Get Programming with JavaScript - Listing 8.03
Listing 8.03 - Accessing array elements
var scores = [ 3, 1, 8, 2 ];
console.log("There are " + scores.length + " scores:");
console.log("The first score is " + scores[0]);
console.log("The second score is " + scores[1]);
console.log("The third score is " + scores[2]);
console.log("The fourth score is " + scores[3]);
Further Adventures
Listing 8.03 - Accessing array elements - Tasks 1&2
- Add a fifth score to the array.
- Add an extra console.log to display the new score.
var scores = [ 3, 1, 8, 2, 200 ];
console.log("There are " + scores.length + " scores:");
console.log("The first score is " + scores[0]);
console.log("The second score is " + scores[1]);
console.log("The third score is " + scores[2]);
console.log("The fourth score is " + scores[3]);
console.log("The fifth score is " + scores[4]);
Listing 8.03 - Accessing array elements - Task 3
- Log the value of the last element to the console.
- Start the message with "The last score is " and concatenate the score to the string.
- Use an expression involving scores.length as the index for the last element.
var scores = [ 3, 1, 8, 2, 200 ];
console.log("There are " + scores.length + " scores:");
console.log("The first score is " + scores[0]);
console.log("The second score is " + scores[1]);
console.log("The third score is " + scores[2]);
console.log("The fourth score is " + scores[3]);
console.log("The fifth score is " + scores[4]);
console.log("The last score is " + scores[scores.length - 1]);
Listing 8.03 - Accessing array elements - Task 4
- Add an extra score to the array and run the program again.
var scores = [ 3, 1, 8, 2, 200, 50 ]; // extra score
console.log("There are " + scores.length + " scores:");
console.log("The first score is " + scores[0]);
console.log("The second score is " + scores[1]);
console.log("The third score is " + scores[2]);
console.log("The fourth score is " + scores[3]);
console.log("The fifth score is " + scores[4]);
console.log("The last score is " + scores[scores.length - 1]);
The length of an array is one greater than the highest index in the array.
To access the last element in an items array, you can use items[items.length - 1].