February 29, 2000 - Associative Arrays
![]() |
February 29, 2000 Associative Arrays Tips: February 2000
Yehuda Shiran, Ph.D.
|
color["yellow"] = "FFFF00";
Such arrays group together related data. These arrays are actually objects,
except that you use the square brackets instead of a dot. Another important
difference is that array specification (square brackets) enables you to refer
to the value of a variable as the property of method specification rather than
the actual literal. For example:
var col = "yellow";
color[col] = "FFFF00";Here is another interesting example:
var w = "write"; document[w]("Hello!")
// prints Hello!
If you replace the array notation with the regular "dot" specification you receive an error:
var w = "write"; document.w("Hello!");
The "dot" notation requires the actual literal specified, as it does not evaluate the written value. You can use associative arrays arrays to create nested objects, resembling multidimensional arrays. For example, you can create an associative array where its subscripts are names of students in a class, so each element of the associative array is an object containg fields such as the student's grade, age, and so on.
Note that associative arrays cannot be created as instances of the built-in Array object. You must use a constructor function to create one. Here is the example with the students:
function studentClass() {
for (var i = 0; i {
this[studentClass.arguments[i] = new student();
}
function student() {
this.grade = null
this.age = null
}
var students = new studentClass("Yehuda", "Yael", "Dikla", "Tomer", "Carmit", "Alon");
students["Yehuda"].grade = 40;
students["Alon"].age = 11;
students["Dikla"].grade = "N/A";
Learn more about associative array usage in JavaScript in Column 58, The Doc Dialer, Part II.


Find a programming school near you