Javascript - eval() `{}` expression

前端 未结 3 696
面向向阳花
面向向阳花 2021-01-24 04:13

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

eval(\"{opacity: 1.0, width: \'132px\'}         


        
相关标签:
3条回答
  • 2021-01-24 05:05

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

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

    Putting it in parentheses changes the parsing context so that an expression is expected, and so the { opens the initializer. (This is the same reason you see self-executing anonymous functions wrapped in parentheses, e.g. (function(){ ... })(); rather than just function(){ ... }();.)

    0 讨论(0)
  • 2021-01-24 05:12

    Try something like this:

    eval("({opacity: 1.0, width: '132px'})");
    
    0 讨论(0)
  • 2021-01-24 05:20

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

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

    0 讨论(0)
提交回复
热议问题