3

I'd like to pass a variable into the key of my monthHash variable here:

 var monthHash = new Array();
  monthHash["JAN"] = "Jan";
  monthHash["FEB"] = "Feb";
  ...
  monthHash["NOV"] = "Nov";
  monthHash["DEV"] = "Dec";

Such that I can do this:

alert(monthHash[the_variable]);

Instead of using a switch case to go through this.

When I try, however, I get an error. Is there a way I can have a variable indicate a string identifier for the key in JavaScript?

0

2 Answers 2

6

The only case that I can see where your code can generate an error is when the_variable is undefined (where you would receive a ReferenceError).

However, Array is not meant to be used for key/value pairs. You should use an object instead:

var monthHash = {};
monthHash['JAN'] = 'Jan';
monthHash['FEB'] = 'Feb';
monthHash['NOV'] = 'Nov';
monthHash['DEC'] = 'Dec';

var the_variable = 'NOV';

alert(monthHash[the_variable]);  // alerts 'Nov'
Sign up to request clarification or add additional context in comments.

Comments

2

Declare it to be an object:

var monthHash = {};
monthHash["JAN"] = ..;

or

var monthHash = {jan: "...", ...}

var x = "jan";
alert(monthHash[x]);

1 Comment

Right - see a lot of literature (quirksmode.org/js/associative.html) on why js arrays are not associative arrays, but use an Object instead. (But I'd use "var monthHash = new Object();)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.