8

Say I have to following code:

var numb = $(selector).length;

And now I want to dynamicly make variables based on this:

var temp+numb = ...

How would I be able to do this?

Edit:

I know some of you will tell me to use an array. Normally I would agree but in my case the var is already an array and I rly see no other solution than creating dynamic names.

icecub
  • 8,615
  • 6
  • 41
  • 70

2 Answers2

5

Variables in Javascript are bound to objects. Objects accept both . and [] notation. So you could do:

var num = 3;    
window["foo"+num] = "foobar";    
console.log(foo3);

PS - Just because you can do that doesn't mean you should, though.

Ayush
  • 41,754
  • 51
  • 164
  • 239
  • Only works in a browser window, not server-side, and really messy. – deitch Sep 15 '13 at 06:53
  • @deitch - hence my suggestion of a scope of his own – mplungjan Sep 15 '13 at 06:53
  • @deitch: Hence the disclaimer at the end of the question. It's hard to offer a better solution (and I'm sure there is one) unless OP shares more context. – Ayush Sep 15 '13 at 06:54
  • I just need it client side. It's for a socketserver chatsystem and I want to use this to dynamicly open tabs for private chats. This is what I needed to get it done. Thanks! – icecub Sep 15 '13 at 07:00
3

In global scope (not recommended):

window["temp"+numb]='somevalue;
window.console && console.log(temp3);

In a scope you create - also works serverside where there is no window scope

var myScope={};
myScope["temp"+numb]="someValue";
window.console && console.log(myScope.temp3);
mplungjan
  • 169,008
  • 28
  • 173
  • 236