How to concatenate variable names in javascript?

How can I concatenate variable names to declare new vars in javascript ?:

var foo = 'var';
var bar = 'Name';

How can I declare a varName variable?

+3
source share
5 answers

Try something like:

window[foo + bar] = "whatever"; 
alert(varName);

do not use the eval function unless you are absolutely sure what is going on. window [] is much safer if all you do is access the variable

+12
source

WARNING: VaporCode! Over my head ...

window[foo + bar] = "contents of variable varName";

It works?

+1
source

(.. var fooName), , eval:

eval('var ' + foo + bar);

eval, , (. ).

It is best to set an object property. Defining a global variable is equivalent to setting a property for a global object window:

window[foo+bar] = 'someVal';

You can substitute windowfor another object if necessary.

+1
source

Locally:

this[foo+bar] = true;

Globally:

window[foo+bar] = true;
0
source

there may be a better way, but eval should do it

eval('var ' + foo + bar);
-3
source

Source: https://habr.com/ru/post/1709259/


All Articles