Hi is it possible to set a var
name from another variable?
Such as I have the var test
with different numbers each time the function is called so I want the number to be a variable name e.g. var test contains ' 1 ' so the new variable would be var 1
. I then want to add a word to this number "word" to make the new variable become var 1word
.
var newNumber = 1;
var newNumber += 'word';
^ becomes ' 1 '
the new var name becomes ' 1word '
edit:
function getNumber(newNumber) // Gets a number, for this example say its the number '1'
{
var newNumber += "something"; //The new varaible will be named "1something" (something can be any word)
}
Hope I haven't made it sound too confusing, thanks.
Everything in Javascript is basically just an associative array. This means you can use array access notation and dot notation more or less interchangeably. Array access notation provides the feature you are looking for:
object["name"]="foo"
will set a name property on the given object.
If you want to create a global variable then use the window object
window["name"]="foo"
You can also use an expression or a variable in the square brackets
window[someVaribale]="foo";
window["name_" + someVariable]="foo";
You can put the variables in an object and index the object using string keys.
For example:
var myData = { };
myData.x1 = 42;
alert(myData["x" + 1]);
You can also initialize the object using object notation:
var myData = { key: 42 };
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