Associative array/Creation: Difference between revisions

Content added Content deleted
m (→‎{{header|Dao}}: formatting)
Line 610: Line 610:


=={{header|JavaScript}}==
=={{header|JavaScript}}==
In Javascript we make an associative array from an empty object, otherwise if we make it from an array we'll get all the Array object's method and properties when we iterate over it
In Javascript we make an associative array from an empty object, otherwise if we make it from an array we'll get all the Array object's method and properties when we iterate over it. Note that this associative array uses strings as its key, but automagically casts other types to strings if used as indices:
<lang javascript>var assoc = {};
<lang javascript>var assoc = {};
assoc['foo'] = 'bar';
assoc['foo'] = 'bar';
assoc['another-key'] = 3;
assoc['another-key'] = 3;
assoc.thirdKey = 'we can also do this!';
assoc.thirdKey = 'we can also do this!';
assoc[2] = 'the index here is the string "2"';
assoc[null] = 'this also works';

for(key in assoc)
for(key in assoc)
{
{
Line 629: Line 632:
When quoting the names you avoid potential collisions with reserved JavaScript key words.
When quoting the names you avoid potential collisions with reserved JavaScript key words.
http://www.quackit.com/javascript/javascript_reserved_words.cfm
http://www.quackit.com/javascript/javascript_reserved_words.cfm

We can also check whether a key exists in an object or not:
<lang javascript>'foo' in assoc // true</lang>


=={{header|Logo}}==
=={{header|Logo}}==