Associative Arrays in JavaScript
Associative arrays are arrays that use strings in place of index numbers, for key elements.
- Using an associative array is quite similar to using a property name with a regular object; you just do it in an array format.
var array_name = new Array(); array_name['key1'] = value1; array_name['key2'] = value2; // ...- "array_name" is the name of the array.
- 'key1', 'key2' are indices (keys) associated with each element (can be written between double or simple quotes, but if they are numbers, do not add quotes).
- "value1", "value2" are the values of the elements (can be: strings, numbers, variables, expressions, or another array). - You can add any number of elements in the Array, with the sintax:
array_name['key'] = value;
• Accessing an associative array is the same as a normal array, except that you use an index string rather than an index number (array_name['key']).
Example:
<script type="text/javascript"><!-- var arrex = new Array(); arrex['site'] = 'http://coursesweb.net'; arrex['course'] = 'Web programming'; arrex['tutorials'] = 'JavaScript'; alert(arrex['site']); // http://coursesweb.net --></script>
Traversing Arrays
You can walk through, or traverse, an array with the "for ... in" or "for each ... in".- Using for ... in
<script type="text/javascript"><!--
var arrex = new Array();
arrex['site'] = 'coursesweb.net';
arrex['course'] = 'Web programming';
arrex['tutorials'] = 'JavaScript';
// parsing the "arrex"
for(var key in arrex) {
// write the index and the value of each element
document.write('Index='+ key+ ' - value='+ arrex[key]+ '<br />');
}
--></script>
- "key" is a variable that holds the index of the current element (can be any variable name) of the array "arrex".- Will display the following result:
Index=site - value=coursesweb.net
Index=course - value=Web programming
Index=tutorials - value=JavaScript
Index=course - value=Web programming
Index=tutorials - value=JavaScript
- Using for each ... in
<script type="text/javascript"><!--
var arrex = new Array();
arrex['site'] = 'coursesweb.net';
arrex['course'] = 'Web programming';
arrex['tutorials'] = 'JavaScript';
// parsing the "arrex"
for each (var elm in arrex) {
document.write(elm+ '<br />');
}
--></script>
- Note the difference from the "for ... in". The "for each ... in" does not get the index component, the variable declared in brackets (here, "elm") stores the element itself.- Will display the following result:
coursesweb.net
Web programming
JavaScript
Web programming
JavaScript
JavaScript Arrays <<-- Previous ----------- Next -->> The Number and Math ...