Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate a dynamic variable name in Javascript

In PHP you can concatenate a variable name like this

$a = 1

${'fruit_' . $a} = 'apple';

The result will lead to the creation of variable $fruit_a

How would I do this in javascript?

like image 709
thank_you Avatar asked Aug 27 '12 20:08

thank_you


2 Answers

You can do this by assigning the variable to a context. For example, to create a dynamically-named global variable in a browser context, you would use:

const a = 1
window['fruit_' + a] = 'apple'

console.log(fruit_1)

If you're in a Node context, you would use global instead of window. If you were trying to create a variable in a method context, you would use this.

like image 68
Ethan Brown Avatar answered Nov 09 '22 22:11

Ethan Brown


Not sure exactly what you are trying to accomplish, but with JavaScript, you could use the following:

> var a = 1;
> var b = {};
> b['fruit_' + a] = 'apple';
> b.fruit_1
"apple"
> b['fruit_1']
"apple"
like image 20
João Silva Avatar answered Nov 09 '22 22:11

João Silva