Ajax JavaScript CSS HTML 5 Gecko XUL Forum

Associative Array in JavaScript

Associative arrays are dynamic objects that  the user redefines as needed. When you assign values ​​to keys in a variable of type Array, the array is transformed into an object, and it loses the attributes and methods of Array. The length attribute has no effect because the variable is not longer of Array type.

We will demonstrate all that and also show how to add a key method to an object to have the number of items it holds when it becomes an associative array.

An associative array is declared or dynamically created

We can create it by assigning a literal to a variable.

var x = ( "one": 1, "two": 2, "three": 3); 

This has implicitly created a variable of type Object.

You can explicitly create an object and assign keys and values:

var o = new Object (); 
 o [ "one"] = 1; 
 o [ "two"] = 2; 
 o [ "three"] = 3; 

What is specific to objects in JavaScript is that attributes are also keys as we shall see in the demonstration.
Thus, the same array can be created more simply:

var oa = new Object (); 
oa.one = 1; 
oa.two = 2; 
oa.three = 3; 

The content is accessed by keys

Whatever the method used to create, you can access content either by keys or by a loop:

var y = o [ "one"];

To get the content element by element, we use a for loop:

for(var key in arr)
{
document.writeln(key + "=" + arr[key]);
}

Keys are assigned to the variable "key", and with the key we access the value.

To know the number of items we have to create a function

Since we no longer have the length attribute of the Array object, it remains to add a method to Object that returns the size of the list:

Object.size = function(arr) 
{
var size = 0;
for (var key in arr)
{
if (arr.hasOwnProperty(key)) size++;
}
return size;
};

This gives the number of items as well:

var s = Object.size(x);

We can also define a simple function that take the object as parameter:

 function size(arr) 
{
var size = 0;
for (var key in arr)
{
if (arr.hasOwnProperty(key)) size++;
}
return size;
};

This gives the number of items as this:

var s = size(x);

Demonstrations of associative arrays

About creating associative arrays with various methods and how to access the items.

Creating an associative array with a litteral

var x = { "one" : 1, "two" : 2, "three": 3 };
for(var i in x)
{
     document.writeln(i + "=" + x[i]);
}

Creating the array with an object

var o = new Object();
o["one"] = 1;
o["two"] = 2;
o["three"] = 3;
for(var i in o)
{
     document.writeln(i + "=" + o[i]);
}

Attributes of a JavaScript object are also keys

var oa = new Object();
oa.one = 1;
oa.two = 2;
oa.three = 3;
for(var i in oa)
{
     document.writeln(i + "=" + x[i]);
}

The length attribute has no value.

See also

© 2010-2011 Xul.fr