Javascript - eval()`{}`表达式 [英] Javascript - eval() `{}` expression

查看:75
本文介绍了Javascript - eval()`{}`表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么不能使用 eval(){opacity:1.0,width:'132px'}这样的字符串c $ c>原样?

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!


推荐答案


为什么字符串可以喜欢{opacity:1.0,width:'132px'}不能使用eval()进行评估?

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

因为文本出现在预期的语句或块的位置,而不是表达式,因此 {表示阻止,而不是对象初始化程序。 (然后 opacity:被解释为标签,然后是语句分隔符[逗号],然后宽度:看起来像另一个标签,在那里无效。)

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.)

将它放在括号中会更改解析上下文以便预期表达式,因此 {打开初始化程序。 (这与您在括号中看到自执行匿名函数的原因相同,例如(function(){...})(); 而不仅仅是 function(){...}(); 。)

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

这篇关于Javascript - eval()`{}`表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆