Task

The goal is to create an associative array (also known as a dictionary, map, or hash).



Related tasks:

 Associative arrays/Iteration
 Hash from two arrays


See also

 Array
 Associative array: Creation, Iteration
 Collections
 Compound data type
 Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
 Linked list
 Queue: Definition, Usage
 Set
 Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
 Stack


var assoc = {};
 
assoc['foo'] = 'bar';
assoc['another-key'] = 3;
 
// dot notation can be used if the property name is a valid identifier
assoc.thirdKey = 'we can also do this!';
assoc[2] = "the index here is the string '2'";
;assoc;
 
//using JavaScript's object literal notation
var assoc = {
  foo: 'bar',
  'another-key': 3 //the key can either be enclosed by quotes or not
};
 
//iterating keys
for (var key in assoc) {
  // hasOwnProperty() method ensures the property isn't inherited
  if (assoc.hasOwnProperty(key)) {
    puts('key:"' + key + '", value:"' + assoc[key] + '"');
  }
}
;assoc;
 
/*
=!EXPECTSTART!=
associativeArray.jsi:12: warn: duplicate var: assoc
assoc ==> { 2:"the index here is the string \'2\'", "another-key":3, foo:"bar", thirdKey:"we can also do this!" }
key:"another-key", value:"3"
key:"foo", value:"bar"
assoc ==> { "another-key":3, foo:"bar" }
=!EXPECTEND!=
*/