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

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

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

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].