X龙@China .Net 'blog

需要的不仅仅是工作,而是通过努力得来的美好将来。
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

为什么要用eval("({a:'b'})")来将字符串转换成json对象

Posted on 2012-02-01 15:41  X龙  阅读(1064)  评论(0编辑  收藏  举报
For the same reson as:

{a: 'abc', b: 'def'};

causes an error but:

( {a: 'abc', b: 'def'} );

does not.

When encountered on the left hand side, the punctuator '{' defines the
start of a block statement, like if{... or while{... etc. The stuff
inside the block is evaluated as if it were a series of statements, so
the script engine attempts to evaluate:

a: 'abc', b: 'def'

and barfs (understandably).

By enclosing the expression in () it is evaluated as if it were the
right hand side of an expression, in which case {} is treated as an
object initialiser. So what you must pass to eval is:

( { /* property names & values */ } )

as a literal string to force it to treat the {} as an object
initialiser.
点击这里给我发消息http://wp.qq.com/index.html