Dynamically select a variable

I have 2 such variables

var variable_1 = "foo"; var variable_2 = "bar"; 

I use the function to capture the input value of a flag, and for each flag that is checked, I want to load a specific variable that depends on the value of the flag.

 $("input:checked").each(function() { $(div).append('variable_'+$(this).val()); } 

So, I would associate the text "variable_" with the value of each flag.

Thanks!

+5
source share
4 answers

Since calling a variable or function from user input is dangerous, and especially if you use only two different variables, you would be better off using a simple if statement.

It is triple if:

 var variable_1 = "foo"; var variable_2 = "bar"; $("input:checked").each(function() { var isChecked = $(this).is(':checked'); var append = (isChecked) ? variable_1 : variable_2; $(div).append(append); } 

Alternatively, you can use the switch statement for multiple values.

0
source

You can use eval to dynamically get any variable values.

 var variable_1 = "foo"; var variable_2 = "bar"; 

$("input:checked").each(function() { $(div).append(eval('variable_'+$(this).val())); }

Note: this is not the best solution because eval has some security issues.

+1
source

Create an object with properties and access these properties through the obj['prop'] notation, see the following code:

 var myObj = {'variable_1': 'foo', 'variable_2': 'bar'}; $("input:checked").each(function() { var dynamicVariableName = 'variable_' + $(this).val() var dynamicVarValue = myObj[dynamicVariableName]; $(div).append(dynamicVar); } 

If your variables are under the window, it is better to create a new global object that contains this variable, and not save these variables as global ones.

0
source

If the variables are global , then you can use

 var y = window["variable_" + x]; 

for reading or

 window["variable_" + x] = y; 

to write them dynamically.

It is best to use an object to store them instead of using separate variables ...

 var data = { variable_1: null, variable_2: null }; ... y = data["variable_" + x]; 

Javascript can also use eval to access dynamic variables, surprisingly even local variables.

 function foo(s) { var x = 12; return eval(s); } console.log(foo("x")); 

and even more surprisingly, it allows you to dynamically create new local variables ...

 var y = 42; function foo(s) { var x = 1; eval(s); return y; // may be global y or a local y defined by code in s } foo("x") // returns 42 foo("var y = 99") // returns 99 (but global y is not changed!) 

but these uses of eval should be considered a mistake rather than a function, and should be avoided (they also make the code impossible in principle to optimize or understand “just don't do it”).

0
source

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


All Articles