Associative array/Iteration: Difference between revisions
Content added Content deleted
(GP) |
|||
Line 986: | Line 986: | ||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
JavaScript does not have associative arrays. |
JavaScript does not have associative arrays until ECMAScript 6 brings Maps. In versions up to ES5.1, you may add properties to an empty object to achieve the same effect. |
||
<lang javascript>var myhash = {}; // |
<lang javascript>var myhash = {}; //a new, empty object |
||
myhash["hello"] = 3; |
myhash["hello"] = 3; |
||
myhash.world = 6; |
myhash.world = 6; //obj.name is equivalent to obj["name"] for certain values of name |
||
myhash["!"] = 9; |
myhash["!"] = 9; |
||
//iterate using for..in loop |
|||
var output = '', // initialise as string |
|||
⚫ | |||
key; |
|||
//ensure key is in object and not in prototype |
|||
⚫ | |||
if (myhash.hasOwnProperty(key)) { |
|||
console.log("Key is: " + key + '. Value is: ' + myhash[key]); |
|||
⚫ | |||
output += " => "; |
|||
} |
|||
output += "value is: " + myhash[key]; // cannot use myhash.key, that would be myhash["key"] |
|||
output += "\n"; |
|||
⚫ | |||
⚫ | |||
//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 |
|||
⚫ | |||
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}}== |
=={{header|Jq}}== |