Too Many Variables? • Remember, a variable is a data structure that can hold a single value at any given time. • What if I want to create an application to track student progress in a class with 50 students? Creating 50 variables will prove inefficient …
Introducing Arrays • An array might prove a better solution to my problem! • An array is a data structure that contains related items that are of the same data type and where each item in the array shares the same name. • In memory, array values occupy contiguous locations.
Multiple Variables in Memory strStu2 strStu3 strStu4 strStu5 strStu1 strStu7 strStu8 strStu6 strStu10 strStu11 strStu12 strStu9
An Array in Memory strWebPrgStudents
Index Order • We number subscripts starting with the number zero (0). We increment by 1 for each subsequent index. • The array’s length refers to the total number of indexes used in an array. The length is always one more than the last index number. Conversely, the last index number is always one less than the array’s length.
One-Dimensional Arrays • A one-dimensional array is a single list of elements subscripts. • Think of a seating chart an elementary school teacher might use. A single row of students is like a one-dimensional array.
0 Janie Bobby 1 Sally 2 Joey 3 Mary 4 RowA Example of a 1D Array Mary is located in RowA
Creating an Empty Array • We can use the Array constructor to create an empty array, with no elements (we can add them later):var strStudents = new Array();
Dimensioning an Array • We can use the Array constructor to create an array of a specific size by supplying the Array constructor with an integer value representing an array's length:var strStudents = new Array(9);
Creating an Array with Specific Values • We can supply the Array constructor with specific values in a comma-delimited list:var strStudents = new Array("James","Ravi","Mary,"Jackson","Alyssa","Alexei");
Assigning Values to an Array • To assign a value to an array, you need to call the array by its name and then provide a subscript to store the new value (the index number goes in a pair of square brackets):strStudents = "Jakob";
Reading Array Values • To read a value from an array, call the array by name and indicate which subscript you want to retrieve (the index number goes in a pair of square brackets): window.alert(strStudents);
The array.length Attribute • We can find how many elements an array has by using the array.length attribute. array.length returns an integer value:intSum = strStudents.length;
Take the next few minutes to examine the file called introArrays_01.html.
Take the next few minutes to examine the file called introArrays_02.html.
Summary • Arrays are data structures that can hold multiple values at the same time. • The values in an array are called elements and they share the same name (the array's name). continued …