icecub
icecub

Reputation: 8773

Javascript: How to dynamicly add a number to a variable name?

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.

Upvotes: 8

Views: 13603

Answers (2)

mplungjan
mplungjan

Reputation: 177885

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);

Upvotes: 3

Ayush
Ayush

Reputation: 42450

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.

Upvotes: 5

Related Questions