Jump to content

Associative array/Iteration: Difference between revisions

(GP)
Line 986:
 
=={{header|JavaScript}}==
JavaScript does not have associative arrays until ECMAScript 6 brings Maps. YouIn canversions up to ES5.1, you may add properties to an empty object, andto that works basicallyachieve the same way:effect.
<lang javascript>var myhash = {}; // a new, empty object
myhash["hello"] = 3;
myhash.world = 6; // obj.name is equivalent to obj["name"] for certain values of name
myhash["!"] = 9;
 
//iterate using for..in loop
var output = '', // initialise as string
for (var key in myhash) {
key;
//ensure key is in object and not in prototype
for (key in myhash) {
if (myhash.hasOwnProperty(key)) {
console.log("Key is: " + outputkey += "key'. Value is: "' + myhash[key]);
}
output += " => ";
}
output += "value is: " + myhash[key]; // cannot use myhash.key, that would be myhash["key"]
output += "\n";
}
}</lang>
 
//iterate using ES5.1 Object.keys() and Array.prototype.Map()
To iterate over values in JavaScript 1.6+:
var keys = Object.keys(); //get Array of object keys (doesn't get prototype keys)
<lang javascript>var myhash = {}; // a new, empty object
keys.map(function (key) {
myhash["hello"] = 3;
console.log("Key is: " + key + '. Value is: ' + myhash[key]);
myhash.world = 6; // obj.name is equivalent to obj["name"] for certain values of name
});</lang>
myhash["!"] = 9;
 
var output = '', // initialise as string
val;
for (val in myhash) {
if (myhash.hasOwnProperty(val)) {
output += "myhash['" + val + "'] is: " + myhash[val];
output += "\n";
}
}</lang>
 
=={{header|Jq}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.