Web DevCenter    
 Published on Web DevCenter (http://www.oreillynet.com/javascript/)
 See this if you're having trouble printing code examples


Working with Object Trees: Part One

by Budi Kurniawan
04/20/2001

JavaScript's ability to work with objects in hierarchy provides a variety of useful applications in the real world.

For example, you can create a folder tree like the one in Windows Explorer. In that application, you can navigate through your file directory system and open a directory by clicking the folder icon. Another example is an XML-based online help system or table of contents for your online books.

When working with objects in JavaScript, you don't have much choice other than to use the "array object." I'll begin this week with a review of the array object in JavaScript. Then in the following article, I'll explain the operations that you need to work with an object tree such as: create an object, append a child object to the root, search an object in the object tree, append an object to another object, and delete an object.

The array object

The array is the only data structure available in JavaScript for storing and manipulating ordered collections of data. Unlike arrays in some other programming languages, a JavaScript array can be used to store different types of data as its elements.

Also, as we get deeper into this concept, you'll see that you can create an array with or without specifying the number of elements. If you create an array without specifying the number of elements, the array behaves like a Vector object in Java where you can add elements arbitrarily.

The array object has one drawback: It's very hard to delete an element in an array.

Creating an array

Creating an array is as easy as assigning a variable with Array() using the new keyword.

var myArray = new Array();

Don't worry about specifying the number of elements because a JavaScript array is perfectly dynamic. You can add elements at any time after the array is created. However, if you must pre-size your array, for any reason, you can do that with the following statement.

var myArray = new Array(20);

The array element count starts from 0. If you specify an array with 20 elements like above, the array has the element index from 0 to 19.

An array also has the length property. The length property adjusts itself when you add an element with an index greater than the array size. For example, in the code in Listing 1, you first define an array with 20 elements, and then add the 21st element to the array. The length property adjusts accordingly.


Listing 1: Creating arrays

<script language="JavaScript">
var myArray = new Array(20);
myArray[20] = "new element.";
// myArray.length value is 21
</script>

Populating an array

You populate an array by assigning values to its elements. For example, the code in Listing 2 creates an array called myArray and populates the first and second elements. In this case, the first element is a number and the second element is a string. Unlike in some other languages where an array must contain elements of the same data type, it is perfectly legal in JavaScript to populate an array with various types of elements.


Listing 2: Populating an array

<script language="JavaScript">
// define an array variable and create an Array object
var myArray = new Array();
// populate the first and second elements
myArray[0] = 1;
myArray[1] = "the name";
</script>

You can even assign an array as an element of another array, as demonstrated in the code in Listing 3.


Listing 3: Assigning an array as an element of another array

<script language="JavaScript">
// define an array variable and create an Array object
var anArray = new Array();
var anotherArray = new Array();
anArray[0] = 1;
// assinging another array as an element of anArray
anArray[1] = anotherArray;
</script>

Knowing how to create and populate an array is basically the foundation for working with an object hierarchy in JavaScript.

The 'delete' operator

Not until Netscape Navigator 4 did JavaScript have the delete operator for deleting an array element. However, as you will soon see, using the delete operator is not an ideal way of deleting an element because it does not decrease the length property of the array.

Listing 4 lists the code that uses the delete operator to delete the third element of an array. Notice how the third element value changes.


Listing 4: Deleting an array element

<html>
<script language="JavaScript">
var myArray = new Array();
myArray[0] = "first element.";
myArray[1] = "second element.";
myArray[2] = "third element.";
document.write(myArray.length + "<br />");
document.write(myArray[2] + "<br />");
delete myArray[2];
document.write(myArray.length + "<br />");
document.write(myArray[2] + "<br />");
</script>
</html>

The code in Listing 4 writes the length property of myArray and the third element of it before and after the third element is deleted using the delete operator. Running the code in Microsoft Internet Explorer 4 and 5, and Netscape Navigator 4, you will see the following result. Note that the length property does not change after you delete the third element.

3
third element.
3
undefined

Running the code in Netscape Navigator 3 gives you the following result:

3
third element.
3
null

The code in Listing 5 deletes an array element and reassigns a new value to the deleted element.


Listing 5: Deleting an array element and reassigning a new value

<html>
<script language="JavaScript">
var myArray = new Array();
myArray[0] = "first element.";
myArray[1] = "second element.";
myArray[2] = "third element.";
document.write(myArray.length + "<br />");
document.write(myArray[1] + "<br />");
delete myArray[1];
document.write(myArray.length + "<br />");
document.write(myArray[1] + "<br />");
myArray[1] = "new element.";
document.write(myArray.length + "<br />");
document.write(myArray[1] + "<br />");
document.write(myArray.length + "<br />");
document.write(myArray[2] + "<br />");
</script>
</html>

Running the code in Listing 5 in Internet Explorer 4 and 5, and Netscape Navigator 4, gives you the following result.

3
second element.
3
undefined
3
new element.
3
third element.

It is obvious that the delete operator does not really remove the element from memory. Therefore, you sometimes need to devise another way to delete an array element.

Truly deleting an array element

By now, you are probably as disappointed with the delete operator as I was. However, my experiment reveals that you can actually decrease the length property of an array, effectively deleting the last element. Consider the code in Listing 6.


Listing 6: Truly deleting an array element

<html>
<script language="JavaScript">

var myArray = new Array();
myArray[0] = "first element.";
myArray[1] = "second element.";
myArray[2] = "third element.";

myArray.length--;

document.write("Array length : " + myArray.length + "<br />");

for (var i=0; i<myArray.length; i++)
  document.write("element " + i + " : " + myArray[i] + "<br />");

document.write("element " + 3 + " : " + myArray[2] + "<br />");

</script>
</html>


The code in Listing 6 produces the following result:

Array length : 2
element 0 : first element.
element 1 : second element.
element 3 : undefined

This shows that after you decrement the length property, the last element is really gone. A cross-browser function to delete the nth element of an array is given in Listing 7.


Listing 7: The deleteElement function

function deleteElement(array, n) {
  //delete the nth element of array
  var length = array.length;
  if (n >= length || n<0)
    return;

  for (var i=n; i<length-1; i++)
    array[i] = array[i+1];
  array.length--;
}

This assumes n is a numeric value. Consider the example in Listing 8 that uses the deleteElement function.


Listing 8: Using the deleteElement function

<html>
<script language="JavaScript">

function deleteElement(array, n) {
  //delete the nth element of array
  var length = array.length;
  if (n >= length || n<0)
    return;

  for (var i=n; i<length-1; i++)
    array[i] = array[i+1];
  array.length--;
}

var myArray = new Array();
myArray[0] = "first element.";
myArray[1] = "second element.";
myArray[2] = "third element.";
myArray[3] = "4th";

document.write("length : " + myArray.length + "<br />");
for (var i=0; i<myArray.length; i++)
  document.write("element " + i + " : " + myArray[i] + "<br />");

deleteElement(myArray, 1);
document.write("length : " + myArray.length + "<br />");
for (var i=0; i<myArray.length; i++)
  document.write("element " + i + " : " + myArray[i] + "<br />");

</script>
</html>


The code in Listing 8 creates and populates an array called myArray and then loops through the myArray Array object to display the value of the length property and all its elements.

for (var i=0; i<myArray.length; i++) 
  document.write("element " + i + " : " + myArray[i] + "<br />");

It then deletes the second element of myArray and redisplays the length property and the contents. The result is as follows.

length : 4
element 0 : first element.
element 1 : second element.
element 2 : third element.
element 3 : 4th
length : 3
element 0 : first element.
element 1 : third element.
element 2 : 4th

Next week

Next week, I'll get into creating, appending, and searching for objects. So play with the examples in this article, then stop back by next week for round two.

Budi Kurniawan is a senior J2EE architect and author.


Return to the JavaScript and CSS DevCenter.

Copyright © 2009 O'Reilly Media, Inc.