Anonymous user
Associative array/Creation: Difference between revisions
→{{header|JavaScript}} Removed inaccurate information, unrecommended use of 'in', wordiness about arrays, and added ES6 Maps
Line 1,107:
=={{header|JavaScript}}==
Javascript object property names (keys) are strings. Other types and expressions can be used with square bracket notation, they are evaluated and converted to strings and the result used as the property name
<lang javascript>var assoc = {};
assoc['foo'] = 'bar';
assoc['another-key'] = 3;
assoc.thirdKey = 'we can also do this!'; // dot notation can be used if the property name▼
assoc[2] = 'the index here is the string "2"';▼
// dot notation can be used if the property name is a valid identifier
//using JavaScript's object literal notation
foo: 'bar',▼
'another-key': 3 //the key can either be enclosed by quotes or not▼
};
//iterating keys
for (var key in assoc) {
if (assoc.hasOwnProperty(key)) {
alert('key:"' + key + '", value:"' + assoc[key] + '"');
Line 1,125 ⟶ 1,133:
}</lang>
ECMAScript 6 (ES6) offers both a map and a weak map implementation. While Objects must use strings, Maps may use objects, functions, and numbers as keys in addition to strings.
▲The hasOwnProperty method can be used to ensure that the property is on the object and not inherited.
fn = function () {},
obj = {};
map.set(fn, 123);
map.set(obj, 'abc');
▲<lang javascript>var assoc = {
map.set('key', 'val');
▲ foo: 'bar',
map.set(3, x => x + x);
▲ 'another-key': 3 //the key can either be enclosed by quotes or not
};</lang>▼
map.get(fn); //=> 123
map.get(function () {}); //=> undefined because not the same function
map.get(obj); //=> 'abc'
map.get({}); //=> undefined because not the same object
map.get('key'); //=> 'val'
map.get(3); //=> (x => x + x)
map.size; //=> 4
▲<lang javascript>'foo' in assoc // true</lang>
//iterating using ES6 for..of syntax
for (var key of map.keys()) {
console.log(key + ' => ' + map.get(key));
=={{header|jq}}==
|