9.2 Array Object
Professor: You often have to handle a set of closely related data, in which case you
can store that da ta into various properties of the same object. Consider, for example, a
rectangle, which can be described by the coordinates of its upper left and lower right
corners, and p erhaps a color. If a rectangle is rotated with in a given coordinate system,
then an angle of rotation is also necessary. All these data co uld be stored as values
of the properties of a single object c alled “rectangle. We will see next week how
you can devise you r own object types or even add properties and methods to existing
objects.
There’s one object type built into the JavaScript language that already allows you
to store and manipulate a collection of data. This is the Array objec t, which is a
specialized form of a JavaScript object. Generally, an array is an ordered collection
of values, which are called elements. It is important that each element has a numeric
position called an index within the array. JavaScript arra ys are zero-based, which
means tha t the first element in an array has the index value zero.
Just like Date, the Array object is a da ta type and we need a constructor in order to
create object instances to work with. You can create an Arra y object in any of the
following three ways:
var a1 = new Array(); //An empty array
var a2 = new Array(5); //An array with room for five elements
var a3 = new Array("start", 6, 2); //An array with three elements
The first line co nstructs an empty Array object to which you can ad d e le ments later.
Let me note that JavaScript arrays are dynamic, which means that they will gr ow or
shrink auto matically as y ou add or remove elements.
In the second line, the elements are not defined but the space in memory is allocated
for f uture needs. I think that you’ll rarely use this secon d constructor, th ough.
In the last of the above lines, an array with three elements is created and the arguments
of the constru ctor become the elements of the new ar ray. Notice that an element of
an array can be of any type. I used a string literal and two num bers but you can use
any type you like, even an object. You’re also not limited to literals but may use an
arbitrary expression for an element.
If you call the Arr ay() constructor with a single argume nt, the second constructor
will be called if that argu ment is a number. Don’t forget tha t and make the same
mistake you did when you c alled the Date() constructor with a single year argument.
If, however, you sup ply a single non-numeric argument, then the third constructor is
called:
//An array with one element set to a string value "I’m single."
var myArray = new Array("I’m single.");
9.2. A rray Object 169
I guess it’s a matter of taste but so me programmers prefer to create arrays using array
literals rather tha n constructors, which use square brackets and commas. We too are
going to use array literals in our course. For example:
var a1 = []; //An empty array
var a2 = [6, 2, "That’s it."]; //An array with three elements
It is very important to have a firm picture of how an array is organized. You can
think of it as a stack of numbered boxes (elements), each holding its own value. You
can access individual values with the [] operator, which you put after the name of
the object with an appropriate index inside. Here’s what the a2 array from the above
example looks like:
6
2
"That’s it."
a2[0]
a2[1]
a2[2]
You can access the second element, for exam ple, simply by writing a2[1] . Note that
you can put an arbitrary expression inside the brackets as long as it evaluates to a
non-negative integer. You’ll soon see that this is a powerful tool in the ha nds of a
progr ammer for accessing array elements.
Finally, you can do with a n individual element just about anything you can do with
an ordinary variable or object of the same type without aecting other elements of the
array whatsoever. For example:
a2[0]++; //Increments the first element
a2[1] = "two"; //Assigns a new value to the second element
console.log(a2[0]); //Writes 7
console.log(a2[1]); //Writes two
It’s time for putting it all together in an example program that ac tually does something.
Imagine you would like to print date s using the full nam es of the m onths and the days
of week, rather than abbreviations as produced by the toString() method. It’s true
that the recent implementations of JavaScript allow you to use full names, in English
as well as in many other languages, but we’ll do it our own way anyhow. If nothing
else, it’s a good exercise. Besides, you may sometimes want to use some more exotic
names like, for example, Middle English names, w hich standard implemen ta tions d o
not support.
Because we cannot compute names using a mathematical formula, the only possible
solution is to define a list of names that we want to use. For example, we can define
an arr ay containing the names of days of the week:
170 Meeting 9. Understanding Arrays and Strings
var dayOfWeek = ["Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"];
This array will serve us as a lookup table. We can look up a name from the ab ove arra y
simply by providing an app ropriate index. The following expression, for example,
returns the second name from th e list:
dayOfWeek[1] //Returns "Monday"
The real power of array s, however, is the ab ility to use an expression as an index.
We can use a value returned by the getDay() metho d as an index to the d ayOfWeek
array:
var today = new Date();
dayOfWeek[today.getDay()]
Maria: Now I see why getDate() and getMonth( ) retu rn values starting from zero
and getDate() returns values starting f rom on e. That’s b ecause you may want to
look up the names of the months and the days of the week from an array, which is
zero based in JavaScript. On the other hand, days of the month don’t have names and
there’s no need for looking anything u p from an array. That’s why numbers starting
from one are returned by g etDate().
Professor: That is indeed so.
Now we have everything that we need to write a program that prints today’s d ate in
words, in an unabbreviated form:
var dayOfWeek = ["Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"];
var month = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November",
"December"];
var today = new Date();
var msg = "Today is ";
msg += dayOfWeek[today.getDay()] + ", ";
msg += month[today.getMonth()] + " ";
msg += today.getDate() + ", ";
msg += today.getFullYear();
document.write(msg); //Writes Today is Sunday, March 1, 2015
In addition to the elements themselves, an Arr ay object also holds the inform ation
about how many elements it h as, which is stored in the length property. Notice that,
because numbering begins with zero, the value of length is always one greater than
the index of the last element. As an example, examine the following fragments of
code:
9.2. A rray Object 171
var a = [5, 88, 21]; //Constructs an array with three elements
a[2] //Returns 21
a.length //Returns 3
a[a.length - 1] //Returns 21
Observe that the last of the above expressions will a lways return th e last element of
the a array regard le ss of its size.
Incidenta lly, it is no t imperative that an arra y contains elements with contiguous in-
dexes starting at zero. If some elements are missing in between, then we say that the
array is sparse. The value of the length property of a sparse array is not equ al to the
number of elements but simply one greater than the index of the last ele ment:
var a = []; //Constructs an empty array
a[5] = 42; //Adds an element to the array and sets its value to 42
a.length //Returns 6
In the above example, I constructed an empty array and then dynamically added the
sixth element to it. The elements a[0] to a[4] do not exist, although some of older
browsers wrongly set them to undefin ed. In practice, however, you will rarely use
sparse arra ys, so I will not go any deeper into the subject.
Mike: I’m just curious: is there any connection between square brac kets used for
accessing a prope rty of an object an d square brac kets used for accessing an element?
Professor: Both work the same . Recall that a property name within brackets should
be a string. Of co urse, JavaScript doesn’t min d at all if you p rovide a numeric in-
dex instead of a string. It simply converts the numeric value to a string according to
the general type-conversion rules. For example, the index 0 becomes the string "0",
which is then used as a property name. In that sense, all indexes are no more than
property names.
That said, there are two fundamental dierences between an arr ay index an d an ordi-
nary object property name. You should, of course, first be able to clearly distinguish
an arr ay index from an object property name. Any property n ame that is an integer
between zero and 2
32
2 is an array index. For exam ple, 3 or 42 are ar ray indexes but
-5 or 1.4 are regular object properties with names "-5" and "1.4", respectively.
Maria: Does that mean that any object typ e can have indexes?
Professor: No, of course not. Indexes as such only apply to ar ray objects. If you
use property names 3 or 42 with a date object, for example, they will behave just like
ordinary properties, and not like true indexes.
Mike: Are you saying that we can add our own properties to an existing object?
Professor: That’s right, but let’s leave that topic for our next meeting.
If you therefore use an integer b etween zero and 2
32
2 as an array p roperty name, it
will behave like a tr ue index. The first diere nce in usin g an index rather than a regular
172 Meeting 9. Understanding Arrays and Strings
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.134.229