11

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?

thank_you
  • 11,001
  • 19
  • 101
  • 185
  • A for loop that counts the number of list items that are dynamic for each user. Then, javascript will insert all the values of the list items into variables and send it through ajax. – thank_you Aug 27 '12 at 20:42

3 Answers3

17

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"
João Silva
  • 89,303
  • 29
  • 152
  • 158
13

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.

Ethan Brown
  • 26,892
  • 4
  • 80
  • 92
  • To get a global variable, use window instead of this. Eg. window ['fruit_' + a] = 'apple'; – yodalr Aug 13 '20 at 12:36
  • If you're in the browser context, @yodalr. If you're in node, it would be `global`. I'm not sure _why_, when I originally answered this, I chose to use `this`, seems odd now. The OP didn't give enough information to determine the scope/context he was trying to create a variable in (shrug). – Ethan Brown Aug 16 '20 at 22:45
0

I came across the same scenario, then I use the switch case to manage the list of variables with sequence numbers like this.

var url = 'stackoverflow.com/questions/12149233/concatenate-a-dynamic/variable-name-in-javascript';
var splittedu = url.substring(url.lastIndexOf('/')+1);
var subsections = splittedu.split("/");

for(let i=1; i<subsections.length-1; i++){
  switch(i) {
    case 1:
      subsection1 = subsections[i];
      break;
    case 2:
      subsection2 = subsections[i];
      break;
    case 3:
      subsection3 = subsections[i];
      break;
    case 4:
      subsection4 = subsections[i];
      break;
 }
Rashid
  • 343
  • 4
  • 14