Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign a value to a dynamic variable using eval?

Tags:

javascript

I got the dynamic variable name doing

varname = "data" + newid + "['" + name + "']";

I would like to assign a value to the dynamic variable. I tried this

eval(varname) = value; 

but it doesn't work. What do I need to do in order to assign a value to the dynamic variable?

like image 968
juria_roberts Avatar asked Sep 04 '12 16:09

juria_roberts


People also ask

What is $$ eval?

$$eval() method. This method runs Array. from(document. querySelectorAll(selector)) within the page and passes the result as the first argument to the pageFunction .

Can eval be used as variable name?

In strict mode, declaring a variable named eval or re-assigning eval is a SyntaxError . If the argument of eval() is not a string, eval() returns the argument unchanged. In the following example, the String constructor is specified and eval() returns a String object rather than evaluating the string.

How do you define a dynamic variable?

A dynamic variable is a variable you can declare for a StreamBase module that can thereafter be referenced by name in expressions in operators and adapters in that module. In the declaration, you can link each dynamic variable to an input or output stream in the containing module.

How do you use eval function?

The Eval function evaluates the string expression and returns its value. For example, Eval("1 + 1") returns 2. If you pass to the Eval function a string that contains the name of a function, the Eval function returns the return value of the function. For example, Eval("Chr$(65)") returns "A".


2 Answers

var data1 = { a: 200 };
var newid = 1;
var name = "a";

var varname = "data"+newid+"['"+name+"']";
var value = 3;
eval(varname + "=" + value); // change data1['a'] from 200 to 3

Having said that, eval is evil. Are you really sure you need to use dynamic variables?

like image 162
João Silva Avatar answered Nov 14 '22 21:11

João Silva


Don't use eval. Don't use dynamic variables.

If you have an unordered group of related data, store it in an object.

var myData = {};
myData[ newid + name ] = value;

although it looks like you are dealing with a dynamic object so

myData[ newid ] = myData[ newid ] || {};
myData[ newid ][ name ] = value;
like image 36
Quentin Avatar answered Nov 14 '22 22:11

Quentin