Closed Thread Icon

Preserved Topic: Arrays: Is this healthy? Pages that link to <a href="https://ozoneasylum.com/backlink?for=18168" title="Pages that link to Preserved Topic: Arrays: Is this healthy?" rel="nofollow" >Preserved Topic: Arrays: Is this healthy?\

 
Author Thread
lallous
Paranoid (IV) Inmate

From: Lebanon
Insane since: May 2001

posted posted 07-31-2001 09:43

in PHP i can do that:

$x = array(99 => 1.2, 1000=>99.1, 21=>111.0, key=> value);
as you see i'm associating a key with a value,
so whenever i do: print $x[99] i'll get 1.2 and whenever i do: print $x[1000] i get 99.

Now As I noticed in javascript that when i do sort of:
x = new Array();
x[1000] = 99.1;
this will allocate 999 empty items and the 1000th item have the value of 99.1
But as you see PHP's array will only allocate as much as i define.

So as i see associative arrays in JavaScript (or at least the way i define them) Is not really healthy...Any recomendation on how to use associative arrays with JavaScript?



mr.maX
Maniac (V) Mad Scientist

From: Belgrade, Serbia
Insane since: Sep 2000

posted posted 07-31-2001 17:46

You're forgetting that JavaScript and PHP are two totally different languages.

In JavaScript you only have indexed arrays and therefore you can't define your own keys (as text or numbers that you can do in PHP)...

Slime
Lunatic (VI) Mad Scientist

From: Massachusetts, USA
Insane since: Mar 2000

posted posted 07-31-2001 18:19

Well, there are two things the [] operator can do in JavaScript. One is access arrays, which you already seem to understand. But there's another thing it can do that may help you out here.

if you have an object, like...

myobj.myprop

you can also access that like this:

myobj["myprop"]

It's a nifty little trick, one of two ways to do "indirection" in JavaScript (the other way being eval(), but I try to avoid that whenever possible).

The thing is, if you use a number

myobj[99]

it *assumes* you're using myobj as an array, and will then turn it into one. *whether or not it actually allocates memory to slots 0 through 98 isn't for sure*. It may not be that efficient. Regardless, if you do something like this instead...

myobj["num" + 99] = "blah blah blah";

then it will treat myobj as an object, and not an array, and myobj.num99 will contain "blah blah blah".

Hope that helps.

Slime
Lunatic (VI) Mad Scientist

From: Massachusetts, USA
Insane since: Mar 2000

posted posted 07-31-2001 18:21

Oh yeah, one more thing, you'll want to predefine myobj like this:

var myobj = new Object();

(as always, "var" is optional.) This lets you start assigning it properties without having the browser complain.

lallous
Paranoid (IV) Inmate

From: Lebanon
Insane since: May 2001

posted posted 08-01-2001 08:32

Hey guys,

First of all I'm not a newbie and I do know the difference between PHP and JavaScript...

Thanks Slime...Object solution looks better than the Array one.

« BackwardsOnwards »

Show Forum Drop Down Menu