CIS 89C  Client-Side Programming with JavaScript

 

Unit 8 - Arrays (week 4)

 

References:

 

McDuffie - Chapter 7 Arrays

 

Topics:

 

Opening statement

What is an array - McDuffie page 188

Declaring an array - McDuffie page 188

Dense arrays -  McDuffie page 192

omit - trivial - Populating an array - McDuffie page 189

Accessing array elements - McDuffie page 189

for loops and arrays - McDuffie page 190

Array literals -  McDuffie page 192

Associative arrays -  McDuffie page 196

Dynamic array lengths - McDuffie page 197

Array methods -  McDuffie page 199

Parallel arrays -  McDuffie page 210

Copying arrays -  McDuffie page 211

Predefined arrays -  McDuffie page 213

delete operator -  McDuffie page 216

Summary -  McDuffie page 218

 

 

***********************************************************

Opening statement

 

Arrays in JavaScript are different than many other languages.

They are not like C.  They are not like perl.

But, they are a little like both of these.

You may be surprised to find all the things you can do with JavaScript arrays.

 

***********************************************************

What is an array

 

An array is a sequential set of data elements.

It is sorta like having a sequential set of variables.

You can address them by subscript integers, like an array in a C array.

You can address them by key name, like an associative array in Perl.

 

The type of data is not specified, as always in JavaScript,

so an array can contain three integers, two floating point numbers, four strings, six Boolean values, five references to objects, and seven references to other arrays.

 

The size of an array is NOT fixed, and may change as you use it.

 

***********************************************************

Declaring an array

 

To set up an array, you use the keyword new.

 

Example:

 

var student_names = new Array();

 

The variable student_names does not actually contain the array;

it contains a reference to the array.

 

Array is the constructor method, used in creating an array.

Notice that the constructor method for an array is spelled with a capital A.

(Do not forget the parentheses, needed with the Array constructor method.)

 

If you wish, you can put the number of array elements you expect to use in the parentheses. 

 

Example:

 

var cars = new Array(5);

 

Is set up for five cars, but you can add more or less than five cars to the array.

The array size can change.

 

 

***********************************************************

Dense arrays

 

You can specify a comma separated list of values as the initial values for the items in the array.  When you do this, the subscripts for them will be:

0  1  2  3  4

just as in C.

 

Example:

 

var weekDays = new Array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");

 

Notice that the list of values is put in the parentheses of the Array constructor.

 

We have seen the arguments to the Array constructor can be nothing, an integer length, or a comma separated list of values.

 

This is called a dense array, because every subscript, beginning from 0, has a corresponding value, up to the size of the array.

 

 

***********************************************************

Accessing array elements

 

Array items can be accessed by subscript integer number, as in C.

 

Example continued:

 

document.write(weekDays[1]);        // writes Tuesday

 

you can also change the values:

 

weekDays[2] = "Mittwosh";              // German for Wednesday

 

You can add item, extending the size of the array:

 

weekDays[9] = "Independence day";

 

Now our array is no longer dense;

entries 6, 7, and 8 are undefined.

 

 

 

***********************************************************

for loops and arrays

 

for loops are usually used to process arrays.

The most common loop is:

 

for (var i = 0; i < weekDays.length; i++)

 

All arrays are objects, and have a length property.

The length is used to process all the values in the array, using the loop:

***********************************************************

Array literals

 

You can create an array without using new.

To do this, put the array item values in a comma separated list inside square brackets.

 

Example:

 

[ "zero", "first", "second", 3 ]

 

These are called literal arrays.

This works fine.  The only problem is that it does not have a name, so it is difficult to use.  You can fix this by creating a variable that has a reference to the array:

 

Example:

 

var count =  [ "zero", "first", "second", 3 ] ;

 

The count variable does not contain the array, but does contain a reference to the array.  So you can code:     count[1]     to get the value     "first"

 

You can leave out one of the values in the middle of the list, to leave that value undefined.  Later you can give it a value.

 

Example:

 

var incompleteCount =  [ "zero",     , "second", 3 ] ;

 

McDuffie warns you that if you put a comma at the end of the list, with no value following it, there may, or may not, be an undefined item at the end of the array.

Different browsers have different interpreters, and handle this differently.

 

This kind of problem makes it very hard to write JavaScript, that will run in all browsers.  In this class we will only use one browser, to keep things simple.

There are libraries of functions used in writing professional JavaScript to alleviate some of these problems.  That is an advanced JavaScript topic, that we will not study.

 

 

***********************************************************

Associative arrays

 

Associative arrays can be set up by using subscripts, other than integers.

These are called keys, whereas integers are called indices.

 

Example:

 

var works = new Array();

 

works["Poe"] = "The Raven";

works["Tolkin"] = "The Hobbit";

works["McKillip"] = "The Forgotten Beasts of Eld";

works["Geisel"] = "The Cat in the Hat";

 

document.write(works["Tolkin"];

document.write(works.Tolkin);

 

The Hobbit

 

So, you see, the subscripts can be integers or anything.

 

Notice the alternative notation, accessing the items in the array as object properties.

 

document.write(works.Tolkin);

 

Which notation is better?  The dot notation is easier to type.

On the other hand, the square bracket notation uses a string, rather than hard coded typed code.  Often you may be processing a string, so the square bracket notation is used.

 

Example:

 

var name;

var first;

var last;

var array;

 

// somehow you set up first and last, and the array.

 

name = first + last;

document.write(array[name]);

 

This is not a very good example, but it points out that often you deal with a string, that is used as a key for the array.

 

We will see that objects in JavaScript are just associative arrays.

This is very much different than languages that have classes of objects, such as C++ and Java.

 

McDuffie points out that, in the Document Object Model, the keys to an array of Elements are their id values.  (Previously the name values were used.)

This is very interesting, but beyond the scope of this course.

 

There are some problems with using associative arrays.

The length property is always zero with associative arrays.

This keeps things from working, that depend on the length.

For example the toString() method, which we will discuss, does not work for associative arrays.

Another example is that the counter loops used to print ordinal arrays does not work for associative arrays.

 

When you do not use string manipulation to determine the key, use of the Object object is considered best practice for associative arrays.  We will introduce the Object object later.

 

***********

for  in loop

 

You can process all the entries in an Array using a for   in loop

 

Example:

 

for (var author in works)

  {

 

  // print the key

  document.write("author: ", author);

 

  // print the value corresponding to the key

  document.write(" work: ", works[author], "<br />");

 

  }

 

in works provides the next key in the Array works; it is assigned to the loop variable, which is named author, in this case.

Each time through the loop, a different key is assigned to the variable author.

Each key is processed once, then when there are no more keys, the loop stops.

 

When you do not use string manipulation to determine the key, use of the Object object is considered best practice for associative arrays.  We will introduce the Object object later.

 

***********************************************************

Dynamic array lengths

 

The length of an array changes, as needed to accommodate the items  you put in the array.

 

***********************************************************

Array methods

 

All arrays are Array objects.

They have a number of Array methods.

These method functions are predefined in JavaScript,

so you can use them with any array.

 

**********

Array to string conversion methods

 

toString()

 

This creates a string.  Many kinds of objects have a toString() method.

For an Array object, it produces a string that is a comma separated list of the array item values.

 

Example:

 

var dogs = ["pooch", "fido", "spot"];

document.write( dogs.toString() );

 

Result:

 

pooch,fido,spot

 

Note that there are no spaces around the commas.

 

join()

 

This creates a string, like toString().  You can specify the separator, used between the items in the string list.  If you do not specify the separator, a comma is used, just like toString()

 

document.write( works.join("-|-");

 

Result:

 

The Raven-|-The Hobbit-|-The Forgotten Beasts of Eld-|-The Cat in the Hat

 

**********

String to Array conversion method

 

This is a String method.  It works on a string, and produces an Array.

 

split()

 

A String is split on the delimiter you specify.

Each piece split off becomes an item in an array.

 

Example:

 

var hatString = "hard-cap-top-fedora";

var hatArray = hatString.split("-");

 

The resulting array contains the four hats.

The dash is the delimiter; it is used to find the end of an entry, and discarded.

 

for (var i = 0; i < hatArray.length; i++)

  {

  document.write(hatArray[i], " ");

  }

 

Result:

 

hard cap top fedora

 

You can specify a maximum number of entries.

 

var threeHatArray = hatString.split("-", 3);

 

This only gets the first three hats.

 

 

**********

copy an Array

 

If you just use an assignment with the variable that references an Array,

it does not copy the array.  It just copies the reference to the Array.

So you get two variables, that both refer to the same Array.

This is usually not what you want.

 

You can create a new empty array.

Then you can use a loop to copy each entry in the old array into the new array.

This works.

 

Alternately, you can use the Array method toString() to create a string containing a comma separated list of the elements from the array.

Then, use the String method split(",") to convert the string into a new array.

This works.

 

var hatArray = ["hard", "cap", "top", "fedora"];

 

var hatString = hatArray.toString();

var hatArrayTwo = hatString.split(",");

hatArray[3] = "bowler"; // change original array

 

Print them and you get the values:

hatString:
hard,cap,top,fedora
Original hatArray, with last item changed:
hard cap top bowler
hatArrayTwo is a different array:
hard cap top fedora

 

If the entries in the array are all primitative elements, this is all you need to do.

On the other hand, if the array contains references, you have similar problems copying them.

 

 

**********

Arrays copy methods

 

concat()

 

The concat() method does NOT change the array you are using.

It creates a new array, that is the concatenation of two arrays.

 

 

workHats = ["hard", "cap"];

dressHats = ["top", "bowler", "fedora"];

 

hats = workHats.concat(dressHats);

 

document.write(hats[4]);          // result is fedora

 

The lengths are:

 

workHats.length    // 2

dressHats.length   // 3

hats.length        // 5

 

(Aside: Willie Brown wears a fedora.)

 

slice()

 

The slice() method does NOT change the array you are using.

It creates a new array, that contains a copy of part of the old array.

 

Example:

 

bigArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

 

smallArray = bigArray.slice(5, 9);

 

smallArray contains:

5  6  7  8

 

A copy is made including the first subscript requested, but

not including the last subscript requested.

 

Another example:

 

var hatArray = ["hard", "cap", "top", "fedora", "bowler"];
var shortHatArray = hatArray.slice(1,4);
for (var i = 0; i < hatArray.length; i++)
{
document.write(hatArray[i], " ");
}
for (var i = 0; i < shortHatArray.length; i++)
{
document.write(shortHatArray[i], " ");
}

Results:
hard cap top fedora bowler
cap top fedora

 

**********

Arrays modification methods

 

reverse()

 

reverse() modifies the array.

It reverses the order of the entries in the array.

 

Example:

 

var count = new Array("zero", "first", 2, 3);

 

for (var i = 0; i < count.length; i++)

  {

  document.write(count[i], " ");

  }

 

Result:

 

zero first 2 3

 

count.reverse();

 

for (var i = 0; i < count.length; i++)

  {

  document.write(count[i], " ");

  }

 

Result:

 

3 2 first zero

 

sort()

 

sort() modifies the array.

It sorts the array.

By default, it sorts the array in alphabetical order.

You can specify a compare function, to sort in a different order.

 

String sort example:

 

var list = new Array("bat", "caw", "ca", "cat", "c", "zebra", 6, 50, "Bat", "Zebra");

list.sort();

document.write(list.toString);

 

Result:

50,6,Bat,Zebra,bat,c,ca,cat,caw,zebra

 

Numerals before upper case letters, upper case letters before lower case letters.,

alphabetical order of strings, short strings before the same string with more added.

Note that the string "50" is before the string "6".

 

If you want a different sort, you must write a function, that is called to compare two items.

 

Numeric sort example:

 

var numbers = new Array(7, 70, 4, 40, 100);

numbers.sort(compare_two_numbers);

document.write(numbers.toString());

 

function compare_two_numbers(first_parameter, second_parameter)

  {

  var return_value;

  var first_number  = parseFloat(first_parameter);  // make sure it is numeric

  var second_number = parseFloat(second_parameter);  // make sure it is numeric

  if ( first_number < second_number )

    { return_value = -1; }

  else if ( first_number == second_number )

    { return_value = 0; }

  else

    { return_value = 1; }

  return return_value;

  }

 

Result:

4,7,40,70,100

 

Rules for a compare function, to be used with sort():

If you want the first item first, return a negative number.

If you do not care which is first, return zero.

If you want the first item last, return a positive number.

 

The sort() function calls your comparison function many times.

It is called to compare two items in the array.

The sort() routine looks at all the items in the array, and sorts them

using one of the standard sort techniques.

 

splice()

 

Do not confuse slice() with splice().

slice() is an Array copy method.

splice() is an Array modification method.

 

Using splice() to remove a sequence of items

 

To use splice() to remove a sequence of items,

specify the subscript of the first item to remove,

and the number of items to remove.

 

Example:

 

// start at hats1[1] and remove 3 hats

var hats1 = ["hard", "cap", "top", "fedora", "bowler"];
// start at hats1[1] and remove 3 hats
var hats2 = hats1.splice(1, 3);

 

Result:

 

hats1: hard,bowler
hats2: cap,top,fedora

 

Notice that the hats are removed.

The hats1 Array has been modified by the splice() method.

 

Using splice() to insert a copy of an array

To use splice() to insert a copy of an array,

specify the subscript of an item,

and zero items to be removed.

A copy of the array will be inserted BEFORE

the specified item.

 

var hats1 = ["hard", "cap", "top", "fedora", "bowler"];
var moreHats = ["helmet", "beret"];
// remove none and insert 2 hats before hats1[1]
hats1.splice(1, 0, moreHats);

Result:

 

hats1: hard,helmet,beret,cap,top,fedora,bowler
moreHats: helmet,beret

 

Using splice() to insert specified items

To use splice() to insert some new items,

specify the subscript of an item,

and zero items to be removed.

The new items will be inserted BEFORE

the specified item.

 

var hats1 = ["hard", "cap", "top", "fedora", "bowler"];
// remove none and insert 2 hats before hats1[1]
hats1.splice(1, 0, "fez", "sombrero");

Result:

 

hats1: hard,fez,sombrero,cap,top,fedora,bowler

 

Using splice() to remove and insert items

splice() can be used to remove and insert items at the same time.

 

Example:

 

var hats1 = ["hard", "cap", "top", "fedora", "bowler"];
// start at hats1[1] insert 2 hats and remove 3 hats
var hats2 = hats1.splice(1, 3, "fez", "sombrero");

Result:

 

hats1: hard,fez,sombrero,bowler
hats2: cap,top,fedora

 

**********

Queue methods

 

Arrays can be used to contain a queue.

To manage a queue, it is necessary to add or delete one item from the queue.

The first item in the queue can be added or removed.

The last item in the queue can be added or removed.

 

Depending on what kind of queuing you are using you may wish to use the first and/or last items when adding or removing an item.

 

pop() removes the last item from an array.

 

push() adds one or more items at the end of the array

We will look at adding one item.

 

shift() removes the first item from an array, and moves the others up to fill the gap.

 

unshift() inserts one or more new item into the beginning of the array, and moves the others back to make room.

We will look at adding one item.

 

***********************************************************

Parallel arrays

 

You can have two arrays, with the same subscripts in both.

Then entry [7] in one array corresponds to entry[7]

in the other array.

 

An alternate technique, which we may consider later is to have one array.

Each item in the array is a reference to an object.  Each object contains the two corresponding items.  This is a better way.

 

 

***********************************************************

Copying arrays

 

We discussed copying arrays when we discussed Array methods.

The main thing is NOT to just copy the variable name,

which just copies the reference to the array.

If you do that, you have two references to the one array.

 

Either use the String methods we discussed,

or use a loop and copy each item from the old array to the new one.

 

***********************************************************

Predefined arrays

 

There are many predefined things in JavaScript.

They represent the browser, the window, the web page,

and the elements in the web page.

 

A few of these are listed in McDuffie on page 214.

 

We will use some of these in this course.

This tie in between JavaScript and the web contents is the reason for using JavaScript.

 

One example is given in the book.

I am not ready to attack this yet.

 

***********************************************************

delete operator

 

Use the delete operator on something, to make it undefined.

 

var stuffArray = ["zero", "one", "two"];

 

delete stuffArray[1];

 

Now the value of the array items is:

 

zero, undefined, two

 

***********************************************************

Summary

 

Arrays are valuable in any programming language.

Arrays are especially valuable in JavaScript.

We will see arrays such as:

 

Every node in the model of the web page has an array of its attributes

Attr[ ]

 

Every node in the model of the web page has an array of its child nodes

Node[ ]

 

et cetera