javascript eval 和对象评估

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4010775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 10:08:17  来源:igfitidea点击:

javascript eval and object evaluation

javascripteval

提问by Fred Thomas

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

我有一个调试框架的一部分,它需要能够运行时 eval 对象。

Specifically, if I have a string like this "{a: 1, b:2}"it needs to evaluate it into an object with members aand bwith 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.

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

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

(顺便说一句,我知道 eval 的危险,但这是实际用户看不到的调试框架的一部分。)

回答by Nick Craver

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.

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