Beginning AngularJS

(WallPaper) #1

ChApter 1 ■ JAvASCrIpt You Need to KNow


Listing 1-26. Working with Arrays


<!DOCTYPE html>




JavaScript Primer





Here, we create an array called myArray and populate it with five string values. As arrays in JavaScript are zero-
based, we start off at zero and finish up at four, for a total of five items. The results follow:


Item at index 0: Andrew
Item at index 1: Monica
Item at index 2: Catie
Item at index 3: Jenna
Item at index 4: Christopher


It can be somewhat tricky trying to keep the index straight, that is, keeping track of which item is at which
position. JavaScript provides the Array.length property, so that you have something with which to work. Listing 1-27
provides an example using the length property.


Listing 1-27. Using the Length Property


...


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

Free download pdf