-1

I can't figure out how to use the name of a variable previously created with eval, without knowing it. I mean:

function getName(menu_name, level){  
    eval("var menu_"+level+"="+menu_name);  
}  

Now how do I get the name of the variable I just created? Probably keep using eval, but I have to put that name into a $.post call as one of my field name.

Thanks in advice.

Kevin Ji
  • 10,479
  • 4
  • 40
  • 63
spacen
  • 1
  • 1
  • If you want to get the name of the variable that you just created, then use the same code that you used to create it in the first place! … but don't do that. `eval` is evil. Variable variables are evil. JavaScript has proper data structures you can use. (See duplicate question). – Quentin Aug 18 '13 at 18:05
  • Why are you using `eval`? It causes a lot of headaches and isn't really worth it. Just use an array. – Kevin Ji Aug 18 '13 at 18:05
  • Thank you. The problem is that I don't know the value of 'level', since it's sent through PHP. What I'm trying to do is having menu_0 the first time, menu_1 the second and so on, where 0,1 are the values of level sent through PHP. – spacen Aug 18 '13 at 18:10

1 Answers1

0

If level is an integer, you can treat it as a numerical index for an array:

var menu = [];
menu[level] = menu_name;

If level is anything else, you can treat it as a key for a dictionary/associative array:

var menu = {};
menu[level] = menu_name;

Then, for either of the solutions, if you want to access your menu_name, simply call menu[level].

Kevin Ji
  • 10,479
  • 4
  • 40
  • 63
  • Level is an integer, but I keep having problems when I try to do this: $.post('url.php', {menu_level : menu_name}, function(e){...}); – spacen Aug 18 '13 at 18:12
  • @user2694388 What's the issue? – Kevin Ji Aug 18 '13 at 18:13
  • Let's put it in other words. I want to create the name of a new variable from two strings, the first being "menu_" and the second being sent through PHP and being "level". Obviously I cannot simply put them together. The problem is because I cannot change the input name in the html form, and as far as I know the parameter I write in the $.post call must be the same as the input name. – spacen Aug 18 '13 at 18:19
  • Just don't create another variable; use the `menu` array and access the right index. – Kevin Ji Aug 18 '13 at 18:48
  • Well then probably I'm not getting that. In PHP it is much easier since you can use ${$var} to create the variable when you don't know its value. The problem is putting that name into the $.post call, can you help me? – spacen Aug 18 '13 at 18:59