Last Updated: 25 Jul 2023

   |   

Author: dordal

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
Last revision Both sides next revision
front-end-tech:javascript:associative-arrays-in-javascript [May 12, 2008 08:49 AM]
dordal
front-end-tech:javascript:associative-arrays-in-javascript [Jul 11, 2023 04:46 PM]
110.249.202.207 removed
Line 1: Line 1:
 += Associative Arrays in JavaScript =
  
 +Unlike PHP (and many other languages), JavaScript doesn't support associative arrays. **Period.** It //does// support objects, which can be used somewhat like an associative array, but without a lot of the usual array goodness. It's an imperfect world, and it bugs me all the time, but it's just the way it is. 
 +
 +In JS, you can set up an array like so:
 +<code javascript>
 +var myArray = new Array();
 +myArray[0] = 'David';
 +myArray[1] = 'Jones';
 +</code>
 +
 +But you can't do:
 +
 +<code javascript>
 +var myArray = new Array();
 +myArray['firstname'] = 'David';             // not possible in JS
 +myArray['lastname'] = 'Jones';              // not possible in JS
 +</code>
 +
 +That's because JavaScript doesn't support the associative (e.g. '' 'firstname' '') index. It only a numerical index (e.g. ''[0]''). 
 +
 +However, you can create an object and assign arbitrarily named properties to it:
 +<code javascript>
 +var myObject = new Object();
 +myObject.firstname = 'David';
 +myObject.lastname = 'Jones';
 +// alternately, use the shorthand syntax:
 +var myObject2 = {firstname: 'David', lastname: 'Jones'};
 +</code>
 +
 +You can access properties of this object with either the dot (''myObject.firstname'') or array (''myObject['firstname']'') notation. You can iterate over all its properties with a for...in loop:
 +<code javascript>
 +for (var index in myObject) {
 +  document.write ('key: ' + index + '; value: ' + myObject[index] + ' ');
 +}
 +</code>
 +
 +The only thing you //can't// do is use the array functions, such as ''join()'' and ''splice()''. Those only work on true Arrays, which were created with the Array constructor and have numerical indexes.