0% found this document useful (0 votes)
11 views

JS Array

The document discusses arrays in JavaScript. It describes how to create arrays using the Array constructor or array initializer syntax. It also covers dynamically changing the length of an array and adding or removing elements. Finally, it lists some common array methods like sort, splice, push, pop and shift.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

JS Array

The document discusses arrays in JavaScript. It describes how to create arrays using the Array constructor or array initializer syntax. It also covers dynamically changing the length of an array and adding or removing elements. Finally, it lists some common array methods like sort, splice, push, pop and shift.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

4.

11 Arrays and
arraylike notation,
We learned earlier that all object properties can be accessed using an Supplies
that objects can therefore be viewed as associative arrays. In addition,. JavaScript special
have
anative function object named Array that can be used to construct objects that section,
this
array characteristics and that inherit a number of array-oriented methods. In simplyyas
we'll learn more about creating and using Array instances, which we'll refer to
arrays.
Section 4.11 Arrays 241

4.11.1 Creating an Array


Onewayto create an array is to use the Array constructor directly in a call with no arguments:

ary1 =. new Array ();


var

Alternatively, an array can be constructed and' initialized with values


morearguments to the Array constructor:
by supplying two or
ar = new Array(4, true, "OK");
var ary2

bcthis statement is executed, ary2 [0] will have the Number value 4, ary2 [1]
the Boolean
true, and ary2 [2] the String value oK. Keep in mind that array
notation is just a way of
ncifying the name oT a property in JavaScript. So an expression such as ary2 [O]
ahe value of theproperty with the name o(a String consisting ofa evaluates
longing to the object referenced by the variable ary2. On the other singlenumeric character)
axerute the expression ary2.0 would generate a syntax error in hand, attempting to
on identifier must be used for the property JavaScript. This is because
name in dot notation, and the syntax rules for
identifiers require that they must not begin with a numeric
such restriction on the actual names that can be character. There is, however, no
I will refer to properties of an array
used for properties: any string c£n be used.
object
tations of natural numbers as the elements of the that have names that are string represen
three elements immediately after the Array array. So ary2 in the second example has
constructor is executed. An array object can also
have other nonelement properties. In fact, every
property named 1ength.When an array is array object is automatically given a special
the case of aryl in the first example),the constructed with ano-argument constructor (as in
value of length will be 0. When
two or more arguments, length is set to the
number
constructed with
of arguments. Thus, after the
creating the variable ary2, ary2.length will have the statement
value 3. We'll have more to say about
this property in the next section.
Another way to create and initialize an array that
of the previous produces identical results to those
example is
var ary3 = [4, true,
"OK"];
Al expression such as the one on the
right side of the assignment in this
l array initializer. This is
for us. essentially a shorthand that implicitly calls the example is called
Array constructor
The elements of a JavaScript array can be
any JavaScript values, including other
Instances
ple, One of Array. This feature can be used to create
way to create atwo-dimensional array is multidimensional arrays. For exam-
I| array2d.js
Var ttt = II
"X", "o", "o" ],
[ "0"; "X", "0" ],
[ "o", "X", "X" ] ];
242 Chapter 4 Client-Side Programming

In this example, the outer one-dimensional array (named ttt) contains three e<ements,
,
itself a one-dimensional array. The notation ttt[1] will evaluate to ar reference to the each
of these internal arrays (the OXOarray). Since this is an array object itself, the second
ttt [1) [2] will evaluate to the value of the third element of this array, 0. notation
arrayscan be created and accessed similarly. .Higher-dimensional
4.11.2 Dynamically Changing Array Length
Just as we can dynamically add properties to any JavaScript object, we can add
properties
to an aray. In particular, in Section 4.11.1, we could follow the code creating ary2 (whie
had three elements) with the statement

ary2[3] = -12.6;

This will create a new property named (as a String) 3with the value-12.6. In addition. the
length property of ary2 will be changed to 4. Thus, unlike arrays in Java, the effective size
of JavaScript arrays can change dynamically. In this way, JavaScript arrays are more lie
instances of the java.util.Vector class than they are like Java arrays.
Elements can also be removed from a JavaScript array by decreasing the value of the
length property. For example, if we next executed the statement
ary2.length = 2;

then the properties 2 and 3 would automatically be removed from ary2.


While we're on the topic of the length property, let me mention a special case that
might cause you trouble if you're not aware of it. If the Array constructor is called with a
single Number argument, then this argument value is assigned to the length property but
no array elements are actually created. As an example, the expression

new Array (200)

creates an array having length 200 but does not actually create or initialize the properties
with names 0 through 199. Similarly, if you increase the length value of an array object,
thisdoes not automatically add any elements (properties with numeric names) to the
Thus, your code should not assume that length always represents the actual array.
elements in an array. number o.

4.11.3 Artay Methods


Every arTay object automatically inherits a number of useful methods. Many of these
methods are described briefly in Table 4.7, and some additional details are given in ns
subsection. Fullalgorithmic details of every method are provided in Section 15.4,4 of ne
ECMAScript specification (ECMA-262].
The argument to the sort() method should be an object representing a funcion.
Thisfunction in turm should take two arguments
representing array elements and retu
Number value. A negative return value indicates that the element corresponding totne
argument should come before the element corresponding to the second in the sorted aeg
Section 4.11 Arrays 243

Methods Return a Reference to


Methods Inherited by Array Objects. Unless Otherwise Specified,
4.7
Called.
TABLE
Which They are
on
Aray
the
Description
Method
comma-separated list.
toString
()
Return a String value representing this array as a
function that
sort
(0bject) Modify this array by sorting it, treating the Object argument as a
specifies sort order (see text).
given by the
splice(Number, Modify this array by adding the third argument as an element at the index
the new element.
0, any type) first argument, shifting elements up one index to make room for
splice(Number, Modify this array by removing a number of clements specified by the seçondelement,
Number) argument (a positive integer), starting with the index specified by the first
and shifting elements down to take the place of those elements removed. Returns an
array of the elements removed.
push(any type) Modify this array by appending an element having the given argument value. Retums
length value for modified array.
pop()
Modify this array by removing its last element (the element at index length-1).
Returns the value of the element removed.
shift() Modify this array by removing its first element (the element at index 0) and shifing
all remaining elements down one index. Returns the value of the element removed.

anosiive value indicates that the second should come before the first, and 0 indicates that
ithe elements can be in either order (for sorting purposes, they are equivalent). For example,
in the program of Figure 4.17, the return value will be positive if the first argument is
reater than the second and negative if the first is less than the second. This will result in an
aray of Number values being sorted into ascending order, as shown. Also notice that the
agument to sort () can be a function expression rather than the name of a function declared
elsewhere.

|| ArrayMethods.js
var numArray = [1,3,8,4,9,7,6,2, 5];
I/ Sort in ascending order
numArray.sort(
Tunction compare (first, second) {
return first - Second;

7nunArray.toString (): 1,2,3,4,5,6,7,8,9


humÀrray.splice(2, 0, 2.5);
" numArray. toString(): 1,2,2.5,3,4,5,6,7,8,9
I/ output of foll owi ng:
S,6,7
window. .alert (numArray .splice(5,3).toString());
windowunArray.toString(): 1,2,2.5,3,4,8,9
.alert (numArray..toString ());
riaURE 4.17 Program illustrating use of several of the methods inherited by array objects.
244 Chapter 4 Client-Side Programming
Figure 4.17 also illustrates two versions of the splice() method, which
for inserting an element into an array (and automatically making room for the is used both
new elen
by shifting other elements) and for removing one or more elements from an
automatically shifting other elements to take the place of those removed). Noticearraythe(and
version of spliçe() that removes eements also returns an array containing the elerme
removed.
The push), pop(), and shift() methods make it easy to implement
basic stack ox s
queue data structures using arrays (if you're not familiar with these data
may want to either read about them in any textbook on data structures or skipstructures, you
of this section). In the case of astack, the length property acts as the the remainder
stack pointer, with
empty stack indicated by a 0 value. The following code illustrates usage of these metha
to implement a stack:

// stack.js
var stack = new Array);

stack.push('H');
stack.push('i');
stack.push('!');
var c3 = stack. pop(); // pops '!"
var c2 = stack.pop (); //popsi
var c1 = stack. pop(); / pops "H
window.alert(c1 + c2 + c3); // displays "Hi!"

You can similarly implement a basic queue structure using


the end of the queue and shift () to remove elements push() to add elements to
from the front of the queue. In this
case, length will point to the back of the queue, and the front of the
Other array methods can be used for additional functionality. For queue will be at index 0.
be used to insert an element at a location other than the example, splice() could
end of the queue, which might be
useful as part of an implementation of priority queues.

You might also like