1

如果我有这个代码:

var x = "alert('eval is evil')";

我可以在没有 eval 的情况下执行这个吗?

我搜索了其他帖子,并没有发现这种情况。

4

5 回答 5

1

javascript 中没有其他函数可以用来执行随机 javascript 代码而不是 eval,但是唯一的其他选择是通过<script>像这样将其附加到页面

var x = "alert('eval is evil')",
    script = document.createElement('script');
script.textContent = x;
script.type = 'text/javascript';
document.head.appendChild(script);
于 2013-10-28T23:55:04.200 回答
0

If you insist on setting x to a string, there's no simple way to avoid eval.* However, you can do this instead:

var x = function() { alert('eval is evil'); };

Or, in modern JS engines:

var x = alert.bind(null, 'eval is evil');

Then you can simply execute x:

x();

*There are techniques to avoiding eval. For instance, you can add a script tag to the document containing the text that you want executed.

于 2013-10-28T23:49:13.823 回答
0

eval基本上是一个嵌入式 JS 解释器,如果你对内置的解释器不满意,你可以自己编写。它可以是复杂的或简单的,取决于您要支持的语言的哪个子集。对于给定的代码示例,这相当简单:

re=/(\w+)\('(.+?)'\)/
code="alert('eval is evil')"
m=code.match(re)
window[m[1]](m[2]) // works

对于严肃的工作,请考虑使用解析器生成器,如 jison 或 peg.js。

于 2013-10-29T00:16:51.857 回答
0

您可以将其添加到Function构造函数中,然后调用它

var x = new Function("alert('this is not much better')");
x();

但是,这也好不到哪里去。以任何一种方式评估 javascript 都容易出错,并且在某些情况下是不安全的,通常,如果您在代码中需要 eval,那么您的应用程序设计是错误的

于 2013-10-28T23:53:23.680 回答
0

这正是eval设计的目的。关键是,你永远不应该编写需要使用eval;的代码。99.99% 的时间你做错了,还有其他选择。

于 2013-10-28T23:41:01.780 回答