Javascript Associative Arrays?

Ok, so first off, everything (I mean EVERYTHING) in Javascript is an object. So there are no such things as “Associative arrays”.

Let’s say you’re coming from PHP and you want to target something by it’s dynamically generated name. You might say:

$things = array();
$things["stuff"] = 123;
$things["otherthings"] = "more stuff";

print_r($things);

It’s fairly easy to callout the values of the variables, like:

echo $things['stuff'];
echo $things['otherthings'];

Let’s say I do the same thing in Javascript

var things = new Array();
things["stuff"] = 123;
things["otherthings"] = "more stuff";

console.dir(things);

I can still call out these things in the array like this

console.log(things['stuff']);
console.log(things["otherthings"]);

However I can also use dot syntax like

console.log(things.stuff)
console.log=(things.otherstuff)

But the object itself is not implicit so we can’t say something like

console.log(things[stuff])

That last one should error out

Ok that’s fine.



			

Leave a Reply

Your email address will not be published. Required fields are marked *