Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use a variable as variable name in JavaScript? [duplicate]

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?


2 Answers

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! :)

like image 30
weirdpanda Avatar answered Aug 05 '26 22:08

weirdpanda



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!