Comparison of programming languages (associative array): Difference between revisions

Content deleted Content added
m Delphi: Corrected a link
DarthKitty (talk | contribs)
m JavaScript: use <code> tags where appropriate; make code snippets more idiomatic
Line 589:
 
====Map and WeakMap====
Modern JavaScript handles associative arrays, using the <code>Map</code> and <code>WeakMap</code> classes. A map does not contain any keys by default.; Itit only contains what is explicitly put into it. The keys and values can be any type (including functions, objects, or any primitive).
 
=====Creation=====
Line 595:
 
<syntaxhighlight lang=JavaScript>
varconst phoneBook = new Map([
["Sally Smart", "555-9999"],
["John Doe", "555-1212"],
["J. Random Hacker", "553-1337"],
]);
</syntaxhighlight>
Line 605:
 
<syntaxhighlight lang=JavaScript>
varconst phoneBook = new Map();
phoneBook.set("Sally Smart", "555-9999");
phoneBook.set("John Doe", "555-1212");
Line 612:
 
=====Access by key=====
Accessing an element of the map can be done with the "<code>get"</code> method:
 
<syntaxhighlight lang=JavaScript>
varconst sallyNumber = phoneBook.get("Sally Smart");
</syntaxhighlight>
 
In this example, the sallyNumber value <code>sallyNumber</code> will now contain the string "555-9999".
 
=====Enumeration=====
Line 625:
<syntaxhighlight lang=JavaScript>
// loop through the collection and display each entry.
for (const [name, number] of phoneBook) {
console.log('`Phone number for ${name} is ${number}'`);
}
</syntaxhighlight>
Line 641:
However, there are important differences that make a map preferable in certain cases. In JavaScript an object is a mapping from property names to values—that is, an associative array with one caveat: the keys of an object must be either a string or a symbol (native objects and primitives implicitly converted to a string keys are allowed). Objects also include one feature unrelated to associative arrays: an object has a prototype, so it contains default keys that could conflict with user-defined keys. So, doing a lookup for a property will point the lookup to the prototype's definition if the object does not define the property.
 
An object literal is written as <code>{ property1 : value1, property2 : value2, ... }</code>. For example:
 
<syntaxhighlight lang=JavaScript>
varconst myObject = {
"Sally Smart" : "555-9999",
"John Doe" : "555-1212",
"J. Random Hacker" : "553-1337",
};
</syntaxhighlight>
 
To prevent the lookup from using the prototype's properties, you can use the <code>Object.setPrototypeOf</code> function:
 
<syntaxhighlight lang=JavaScript>
Line 657:
</syntaxhighlight>
 
As of ECMAScript 5 (ES5), the prototype can also be bypassed by using <code>Object.create(null)</code>:
 
<syntaxhighlight lang=JavaScript>
varconst myObject = Object.create(null);
 
Object.assign(myObject, {
"Sally Smart" : "555-9999",
"John Doe" : "555-1212",
"J. Random Hacker" : "553-1337",
});
</syntaxhighlight>
Line 672:
 
<syntaxhighlight lang=JavaScript>
varconst myOtherObject = { foo : 42, bar : false };
</syntaxhighlight>
 
Line 685:
 
<syntaxhighlight lang=JavaScript>
for (varconst property in myObject) {
var const value = myObject[property];
console.log("`myObject[" + ${property + "}] = " + ${value}`);
}
</syntaxhighlight>
Line 694:
 
<syntaxhighlight lang=JavaScript>
for (const [property, value] of Object.entries(myObject)) {
console.log(`${property} = ${value}`);
}
</syntaxhighlight>
Line 708:
 
<syntaxhighlight lang=JavaScript>
myObject[1] // key is "1"; note that myObject[1] == myObject['"1'"]
myObject[['"a'",' "b'"]] // key is "a,b"
myObject[{ toString:function() { return '"hello world'"; } }] // key is "hello world"
</syntaxhighlight>
 
In modern JavaScript it's considered bad form to use the Array type as an associative array. Consensus is that the Object type and <code>Map</code>/<code>WeakMap</code> classes are best for this purpose. The reasoning behind this is that if Array is extended via prototype and Object is kept pristine, 'for( and for-in)' loops will work as expected on associative 'arrays'. This issue has been brought to the fore by the popularity of JavaScript frameworks that make heavy and sometimes indiscriminate use of prototypes to extend JavaScript's inbuilt types.
 
See [http://blog.metawrap.com/2006/05/30/june-6th-is-javascript-array-and-object-prototype-awareness-day/ JavaScript Array And Object Prototype Awareness Day] for more information on the issue.