"ASM" <st*********************@wanadoo.fr.invalid> wrote in message
news:43**********************@news.wanadoo.fr...
Jim Davis wrote:
And if it IS very large or you search it a lot why not set up a hash
table? Then it's just "if ( myHash["Jane"] ) {};" Instant results with
no fuss.
Just my opinion of course - which doesn't change the fact that
McKirahan's solution will, indeed, work just fine. ;^)
tbl = new Array("frank", "jim'n'jane", "moriaux", "toto", "foo");
alert(tbl['toto']);
returns : undefined
I'm sorry... I think you've missed something. This isn't a hash table so it
would, of course, return "undefined".
A "normal" array, as you've built, is indexed by a count (numbers) -
1,2,3,4,5,etc. You can access any element by it's numerical position in the
array (JavaScript also supports numerically indexed arrays where the numbers
are not in order, but leave them out of the discussion for now). You can do
"MyArray[1]", "MyArray[4]", etc. You can loop over the array easily using a
counter loop.
A hash table can be most easily thought (at least by me) of an array indexed
by values (the values can be anything: strings, object references,
whatever). In many languages these values are called "keys" and in
JavaScript they're object properties. You would access values by
"MyHash[MyKeyValue]" (just as you would access any object property using
bracket notation).
So, to demonstrate, try this:
tbl = {"frank": null, "jim'n'jane": null, "moriaux": null, "toto": null,
"foo": null}
This (object literal notation) will create an object where each property is
the "name" and the value is "null". If you need access to array methods in
your hash (most of the time you don't) you might also do this:
tbl = new Array();
tbl["frank"] = null;
tbl["jim'n'jane"] = null;
tbl["moriaux"] = null;
tbl["toto"] = null;
tbl["foo"] = null;
(But, as noted elsewhere, you cannot use any existing array properties -
namely "length" as a key name.)
In either case however try alert(tbl['toto']); again.
This is a very powerful aspect of the language that just doesn't get use "in
the wild".
Jim Davis