Javascript associative variable

I would like to pass the variable to the key of my variable monthHashhere:

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

So that I can do this:

alert(monthHash[the_variable]);

Instead of using a switch to get through this.

When I try, I get an error message. Is there a way that a variable can contain a string identifier for a key in JavaScript?

+3
source share
2 answers

The only time I can see where your code might generate an error is when it is the_variableundefined (where you get it ReferenceError).

Array /. :

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

var the_variable = 'NOV';

alert(monthHash[the_variable]);  // alerts 'Nov'
+6

:

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

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

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

Source: https://habr.com/ru/post/1751278/


All Articles