Online Documentation Server
 ÏÎÈÑÊ
ods.com.ua Web
 ÊÀÒÅÃÎÐÈÈ
Home
Programming
Net technology
Unixes
Security
RFC, HOWTO
Web technology
Data bases
Other docs

 


 ÏÎÄÏÈÑÊÀ

 Î ÊÎÏÈÐÀÉÒÀÕ
Âñÿ ïðåäîñòàâëåííàÿ íà ýòîì ñåðâåðå èíôîðìàöèÿ ñîáðàíà íàìè èç ðàçíûõ èñòî÷íèêîâ. Åñëè Âàì êàæåòñÿ, ÷òî ïóáëèêàöèÿ êàêèõ-òî äîêóìåíòîâ íàðóøàåò ÷üè-ëèáî àâòîðñêèå ïðàâà, ñîîáùèòå íàì îá ýòîì.




Previous Table of Contents Next

Creating an associative array is not difficult. Array elements are created according to the names of the students accepted as parameters by the function studentClass(). The second function is rather strange—it contains no statements. When you create an instance you can use an “empty” constructor function. You may recall from an earlier discussion that objects may be extended by simply assigning values to them. So, the statement this[arguments[i]] = new student() just makes sure each element of the associative array is an object. The global statements later create the properties simply by assigning them values.

Another important concept to remember is that associative arrays are not explicit arrays. You can also refer to them using the “dot” syntax as in:

students.Alon.age

Suppose you created a database structure listing all the students in a class with their ages and grades. Assume that both fields are fed with the proper values. You can let the user view these values via a prompt dialog box. For example:

var grade = students[prompt("Enter name:", "John Doe")].grade
document.write(grade)

In this case you must use the array convention because you are prompting the user for the property name. You can use the dot notation only when you know the property name. If you use the dot notation:

students.prompt(...)

JavaScript assumes you are referring to a method of the students object named prompt(), which does not exist at all, of course.

Populating an Associative Array

Creating a dense array is simple when using regular arrays. You simply create the array with the desired values. However, associative arrays require two real values for each element, the key (subscript) and the value. You can create a constructor function to create and populate associative arrays:

function AssociativeArray() {
  for (var i = 0; i < arguments.length – 1; i += 2) {
 this[arguments[i]] = arguments[i + 1]
  }
}

You can use this function to create associative arrays in the following format:

var ar = new AssociativeArray("red", "FF0000", "green", "00FF00",
 "blue", "0000FF")
document.write("green = " + ar["green"] + "<BR>")
var col = "blue"
document.write("blue = " + ar[col] + "<BR>")
document.write("red = " + ar.red)

The relative output of this script is:

green = 00FF00
blue = 0000FF
red = FF0000

Let’s take a look at the constructor function. It accepts the keys of the array elements followed by their corresponding values. Each key must be followed by its own value. The function loops through the arguments and terminates after it has reached the argument before the last one. During each pass through the function, a property of the calling object is created (an “element” in the array lexicon). The key of the property, or element, is the current argument whereas its value is extracted from the following argument. The loop counter is advanced by two after each execution of the block, because each element of the associative array is related to two arguments—its key and its value. Although an associative array is primarily a regular object, this constructor must use square brackets, the array notation, for reference and initialization because the values of the keys (subscripts) are not literals, but rather values stored as parameters.

Splitting a String into an Associative Array

The split() method splits a string by a specified delimiter to a real instance of an Array object. For example:

var str = "a;b;c;d;e;f"
var ar = str.split(";") // ar[0] == "a", ar[1] == "b", ...

Let’s use the split() method to create a function named associativeSplit() as a prototype of the String object. Here it is:

function associativeSplit(del) {
  var tempAr = new Array()
  tempAr = this.split(del)
  var ar = new Obj() // not an array, just an object
  for (var i = 0; i < tempAr.length – 1; i += 2) {
 ar[tempAr[i]] = tempAr[i + 1]
  }
  return ar
}

function Obj() { }

String.prototype.associativeSplit = associativeSplit

Notice the use of an empty function to create an object. At first, the function splits the string via the regular method to a regular array. It then loops through the array, using the next element as the key of an element in the associative array and its following element as the value of the same element in the associative array. Upon completion, the function returns the associative array. The function is then declared as a prototype of the built-in String object, applying to all strings.

Now take a look at an example:

var str = "a b c d e f"
var ar1 = str.associativeSplit(" ")

document.write(ar1.a + "<BR>")
document.write(ar1.b + "<BR>")
document.write(ar1["c"] + "<BR>")
document.write(ar1["d"] + "<BR>")
// document.write(ar1[e] + "<BR>")
document.write(ar1.f + "<BR>")

Note that “associative array” is not a JavaScript term, but rather a regular object. We just prefer to refer to its properties via the array notation.

Summary

In this chapter we learned about arrays in JavaScript. Unlike most languages, array in JavaScript is a regular object, not an explicit data type of its own. We discussed the Array object, including its properties and methods. Another important concept brought together in this chapter was constructor functions and prototypes, used mainly to simulate array methods featured by Perl. By now, you should have a grasp on arrays and constructor functions, two very important elements of the language. You should also know how to create and use two-dimensional arrays, as well as multidimensional ones, although they are rarely used. In this chapter we also introduced the term “associative arrays.” Such arrays are regular objects with regular properties, but they remind us of associative arrays, widely used in other languages such as Perl. In following chapters we shall look further into JavaScript’s object model, while arrays and constructors will serve as the base of some scripts.

Previous Table of Contents Next


With any suggestions or questions please feel free to contact us