Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript associative array by variable

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?

like image 858
Incognito Avatar asked Jun 04 '26 10:06

Incognito


2 Answers

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'
like image 193
Daniel Vassallo Avatar answered Jun 06 '26 00:06

Daniel Vassallo


Declare it to be an object:

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

or

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

var x = "jan";
alert(monthHash[x]);
like image 31
jvliwanag Avatar answered Jun 06 '26 00:06

jvliwanag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!