Lookup table...if / else vs. switch vs. hash?

C

cjl

Hey all:

I need to get some user input which will be a six digit number. I will
split it into two character pairs. Each pair will need to be "looked
up", for example:

if firstPair == '01' then variable = "Monkey";
else if firstPair == '02' then variable = "Chicken";
etc..


So I think I could do this with if / else statements chained together,
and I think I could do this with a switch statement.

I remember someone showing a way to do this with a hash, but I can't
find it anywhere.

Is there a javascript idiom that is more elegant for this problem than
if / else or switch?

-CJL
 
M

Michael Winter

On 13/10/2005 13:26, cjl wrote:

[snip]
if firstPair == '01' then variable = "Monkey";
else if firstPair == '02' then variable = "Chicken";
etc..

A lookup table would be the nicest solution:

var pairs = { '01' : 'Monkey',
'02' : 'Chicken' },
variable = pairs[firstPair];

[snip]
I remember someone showing a way to do this with a hash, but I can't
find it anywhere.

Note that the object above, pairs, is not a hash table. It's just an
object that's being used like a lookup table, where property names are
mapped to values.

[snip]

Mike
 
C

cjl

Mike:

Thanks. That is exactly what I was looking for.

I guess I may have been using the terms lookup table and hash
incorrectly, but that's what I get for trying to sound like I know
about computer programming using terms that I've seen on Slashdot.

-CJL
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top