Concatenate A Dynamic Variable Name In Javascript


Answer :

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"


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.



Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable