javascript评估和对象评估 [英] javascript eval and object evaluation

查看:62
本文介绍了javascript评估和对象评估的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个调试框架的一部分,该框架需要能够运行时间评估对象.

I have a part of a debugging framework that needs to be able to run time eval objects.

具体来说,如果我有这样的字符串"{a: 1, b:2}",则需要将其评估为具有这些值的成员ab的对象.但是,如果我eval("{a: 1, b:2}")这样做,它似乎会将其评估为声明,并说出有关非法标签的内容.

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 + ")");

但是,如果浏览器支持,则应首先使用JSON.parse().

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

这篇关于javascript评估和对象评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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