开发者

javascript eval and object evaluation

I have a part of a debugging framework开发者_开发技巧 that needs to be able to run time eval objects.

Specifically, if I have a string like this "{a: 1, b:2}" it needs to evaluate it into an object with members a and b with those values. However, if I do eval("{a: 1, b:2}") it seems to evaluate it as a statement, and says something about an illegal label.

I have hacked it so that it evaluates like this:

eval("var x=" + str + "; x;");

which seems to work, but seems like a horrible hack. Any suggestions on how to do this better?

(BTW, I am aware of the dangers of eval, but this is part of a debugging framework that will not be seen by actual users.)


You can do it using () to have it parse it as an object, rather than a statement, like this:

eval("(" + str + ")");

Though, you should use JSON.parse() first, if the browser supports it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜