Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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.

like image 642
icecub Avatar asked Sep 15 '13 06:09

icecub


People also ask

How do you assign a value to a variable in JavaScript?

You can assign a value to a variable using the = operator when you declare it or after the declaration and before accessing it. In the above example, the msg variable is declared first and then assigned a string value in the next statement.

Can you use numbers in variable names JavaScript?

JavaScript has only a few rules for variable names: The first character must be a letter or an underscore (_). You can't use a number as the first character. The rest of the variable name can include any letter, any number, or the underscore.

Can a variable name include a number?

After the first initial letter, variable names can also contain letters and numbers. No spaces or special characters, however, are allowed.


2 Answers

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.

like image 95
xbonez Avatar answered Dec 08 '22 01:12

xbonez


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);
like image 24
mplungjan Avatar answered Dec 07 '22 23:12

mplungjan