Javascript - eval () `{}` expression

Why can't a line like "{opacity: 1.0, width: '132px'}" be evaluated with eval() as it is?

 eval("{opacity: 1.0, width: '132px'}"); // invalid label // {opacity: 1.0, width: '132px'} // ---------------ꜛ eval("v = {opacity: 1.0, width: '132px'}"); // works! 
+1
source share
3 answers

Why can't a line like "{opacity: 1.0, width: '132px'}" be evaluated using eval () as it is?

Since the text occurs where the operator or block is expected, not the expression, and therefore { denotes the beginning of the block, and not the beginning of the object initializer . (And then opacity: interpreted as a label , followed by an operator separator [comma], and then width: looks like another label that is invalid there.)

Putting in parentheses changes the parsing context so that an expression is expected, and therefore { opens the initializer. (For the same reason, you see self-signed anonymous functions enclosed in parentheses, for example (function(){ ... })(); and not just function(){ ... }(); )

+6
source

Why can't a line like "{opacity: 1.0, width: '132px'}" be evaluated using eval () as it is?

Because {opacity: 1.0, width: '132px'} is invalid javascript as-is. Try to put this statement as it is, and you will get a js error. On the other hand, v = {opacity: 1.0, width: '132px'} is valid javascript.

+3
source

Try something like this:

 eval("({opacity: 1.0, width: '132px'})"); 
+1
source

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


All Articles