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.
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.
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.
After the first initial letter, variable names can also contain letters and numbers. No spaces or special characters, however, are allowed.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With