spacer
Yehuda Shiran February 29, 2000
Associative Arrays
Tips: February 2000

Yehuda Shiran, Ph.D.
Doc JavaScript

Developer News
Microsoft Shows Off Silverlight 4, IE9 Plans
Metasploit Expands Vulnerability Test Framework
HyperCard Reborn?

Associative arrays use strings as subscripts. For example, an element of the array can be:
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 < arguments.length; ++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.


People who read this tip also read these tips:

Look for similar tips by subject:

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs

webref The latest from WebReference.com Browse >
Rolling Out Your Own HTML Application Version Control · HTML 5: Client-side Storage · Working with Ajax Server Extensions
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Wi-Fi Product Watch, November 2009 · Chip Market Recovering From '08 Collapse · Low-Cost Tools to Kickstart Your New Business