Closed Thread Icon

Topic awaiting preservation: Associative Arrays (Page 1 of 1) Pages that link to <a href="https://ozoneasylum.com/backlink?for=22590" title="Pages that link to Topic awaiting preservation: Associative Arrays (Page 1 of 1)" rel="nofollow" >Topic awaiting preservation: Associative Arrays <span class="small">(Page 1 of 1)</span>\

 
Iron Wallaby
Paranoid (IV) Inmate

From: USA
Insane since: May 2004

posted posted 07-17-2004 05:56

I know that the shortcut for defining an array is var foo = [bar, baz, quux, quuux, ... ]; and so forth.

What I am looking for is a comparable "shorthand" for defining an associative array. All I can currently find is that I should do this:

var foo = [];
foo["bar"] = "fred";
foo["baz"] = "barney";
foo["quux"] = "wilma";
foo["quuux"] = "betty";
...

In Perl, for example, this could be done with my $foo = { "bar" => "fred", "baz" => "barney", "quux" => "wilma", "quuux" => "betty"}; or something of that sort (I haven't done that in a while, heh...). So I am wondering if anyone has found such a thing.

Thanks, all.

"Any sufficiently advanced technology is indistinguishable from magic." -- Arthur C. Clarke
"Any sufficiently arcane magic is indistinguishable from technology." -- P. David Lebling

Slime
Lunatic (VI) Mad Scientist

From: Massachusetts, USA
Insane since: Mar 2000

posted posted 07-17-2004 07:57

Well, foo["bar"] = "fred" is equivalent to foo.bar = "fred". So, what you're essentially doing is assigning property values to an object.

Therefore, you should use the object literal syntax:

var foo = {
bar: "fred",
baz: "barney"
...
};

I'm not sure if it's commas or semicolons or what inbetween. Someone will probably correct me, but otherwise search google for "javascript object literal syntax" to get the details that I messed up from bad memory.


 

norm
Paranoid (IV) Inmate

From: [s]underwater[/s] under-snow in Juneau
Insane since: Sep 2002

posted posted 07-17-2004 08:26

Commas work just fine for separating properties in new Object Literals. What I want to know is if they take up the same amount of memory (item for item) as an array. Anyone know?

/* Sure, go ahead and code in your fancy IDE. Just remember: it's all fun and games until someone puts an $i out */

Iron Wallaby
Paranoid (IV) Inmate

From: USA
Insane since: May 2004

posted posted 07-17-2004 16:20

That does the trick exactly. Thanks, slime.

norm: They should not take the same space, since they have more data associated with them (the search string). So an associative array is, typically, less efficient but more versatile.

Even so, in Javascript, memory management is not usually too much of an issue.

"Any sufficiently advanced technology is indistinguishable from magic." -- Arthur C. Clarke
"Any sufficiently arcane magic is indistinguishable from technology." -- P. David Lebling

« BackwardsOnwards »

Show Forum Drop Down Menu