PDA

View Full Version : Variables with a Name that's a String?



???
06-17-2007, 04:15 PM
I asked my friend about this once... he said you do:

var this["astringforthename"] = "blah";
alert(var this["astringforthename"]);

I tried that in Firefox, and it didn't work. Can someone either tell me why it didn't work and/or how you make a variables name be a string?

shachi
06-17-2007, 04:19 PM
this is a reserved keyword and you also need to initialize the array before you can use it. Instead do:



var that = [];
that["key"] = "value";


and you don't need the var inside the alert:



alert(that["key"]);


Combined:



var that = [];
that["key"] = "value";
alert(that["key"]);

???
06-17-2007, 04:23 PM
Opse, I didnt mean to have the var in the alert part, sorry.

???
06-17-2007, 04:25 PM
So it's just an array, but instead of having a numbers, you have strings? So you have to define a variable?

Twey
06-17-2007, 08:21 PM
Don't do this with arrays. All objects in ECMAScript can be modified in this way. Using Array is a bad choice because ECMAScript arrays are meant to be unique, and it's entirely reasonable for a script to extend Array, breaking the only method of enumeration available for such hashes, the for..in loop. Instead, either use a plain Object:
var myhash = {};
myhash['fish'] = 5;

(print || alert)(myhash['fish']); // 5
(print || alert)(myhash.fish); // 5This has the added advantage that you can use the standard object literal:
var myhash = {
'fish' : 5
};

(print || alert)(myhash['fish']); // 5
(print || alert)(myhash.fish); // 5You can also create your own Hash constructor, or use one of the ones available on the Internet (have a look for Rick Measham's version, in particular: I can't seem to find it, but I remember it being a fairly well-implemented one). This option allows you to create new methods for your hashes without the fear of breaking existing code (always try to avoid extending Object).

Trinithis
06-17-2007, 08:31 PM
var myhash = {
'fish' : 5
};

Is there a reason to put quotes around fish? It seems to work fine without them when referencing them with dot notation. Or is it so you can reference things like '* gsd s\'s' with the bracket notation?

Oh, and what's the difference between an object hierarchy and a hash hierarchy?

Twey
06-17-2007, 08:42 PM
I can't remember the exact grammar as to why not using quotes works here, perhaps it's just a special case. Either way, using quotes is (in my opinion) neater, and allows one to have property names containing special characters such as spaces, which is obviously desirable in a hash.
Oh, and what's the difference between an object hierarchy and a hash hierarchy?In ECMAScript all objects are also hashes, so nothing.

mwinter
06-17-2007, 09:05 PM
var myhash = {
'fish' : 5
};

Is there a reason to put quotes around fish?

Not when the property name conforms to the Identifier grammar production, or it is a number. Otherwise, quotes are necessary.