Javascript - eval() `{}` expression

北城以北 提交于 2019-12-02 08:26:10

问题


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

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

// invalid label
// {opacity: 1.0, width: '132px'}
// ---------------ꜛ

eval("v = {opacity: 1.0, width: '132px'}");

// works!

回答1:


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(){ ... }();.)




回答2:


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.




回答3:


Try something like this:

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


来源:https://stackoverflow.com/questions/9943278/javascript-eval-expression

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!