I am trying to use a variable as another variables name. For example, I have the following:
var dynamicname = 'name1_'
And I am trying to set it as the name of a new variable like this:
dynamicname + '2' = 'myvalue'
This obviously isn't working but is there a way to achieve this? Would eval be suitable?
To my knowledge, this is the best method.
window["varname"]=32;
console.log(varname)
Slightly off, but a possible answer to this using objects can be something along the lines of:
const obj = {
[ dynamicNameVar + '2' ]: ...
}
Or, for the old-school folks,
var obj = {};
obj[dynamicNameVar + '2'] = ...
I hope this helps! :)
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