Beginning AngularJS

(WallPaper) #1
ChApter 1 ■ JAvASCrIpt You Need to KNow

// Display the first item
console.log("The first item is: " + myArray[0]);
// Dislay the last item
console.log("The last item is: " + myArray[myArray.length - 1]);


...


Listing 1-27 is similar to Listing 1-26, but instead of hard-coding the index values, we use the length property to
calculate the current position. Note the need to cater to the zero-based nature of arrays. Accessing the last item in the
array requires us to subtract 1 from the length property.


The first item is: Andrew
The last item is: Christopher


Array Literals

The manner in which we have gone about creating arrays so far might be considered the long way. I will show you an
alternative way, which is more concise and, arguably, more readable when you are creating an array and populating it
with values all in one go round. Instead of doing this:


var myArray = [];
myArray[0] = "Andrew";
myArray[1] = "Monica";
myArray[2] = "Catie";
myArray[3] = "Jenna";
myArray[4] = "Christopher";


you can achieve the same result doing this:


var myArray = ["Andrew","Monica","Catie","Jenna","Christopher"];


This is certainly the style I prefer in most cases. I chose the first approach mainly because it was more
demonstrative of the index-based nature of arrays.


Enumerating and Modifying Array Values

The usual way of enumerating an array is to use a for loop, which I covered in the “Control Flow” section earlier in
this chapter. Listing 1-28 shows this approach in action.


Listing 1-28. Enumerating an Array


var myArray = ["Andrew","Monica","Catie","Jenna","Christopher"];


for(var i = 0; i < myArray.length; i++) {
console.log(myArray[i]);
}

Free download pdf