在 JavaScript 中使用 eval() 的主要好处是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10474306/
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
What's the main benefit of using eval() in JavaScript?
提问by Coffee
I know this may be a newbie question, but I'm curious as to the main benefit of eval()
- where would it be used best? I appreciate any info.
我知道这可能是一个新手问题,但我很好奇它的主要好处 eval()
- 它最好用在哪里?我很欣赏任何信息。
采纳答案by Guffa
The eval
function is best used: Never.
eval
最好使用该功能:从不。
It's purpose is to evaluate a string as a Javascript expression. Example:
它的目的是将字符串评估为 Javascript 表达式。例子:
eval('x = 42');
It has been used a lot before, because a lot of people didn't know how to write the proper code for what they wanted to do. For example when using a dynamic name for a field:
它以前被使用过很多次,因为很多人不知道如何为他们想做的事情编写正确的代码。例如,当对字段使用动态名称时:
eval('document.frm.'+frmName).value = text;
The proper way to do that would be:
正确的做法是:
document.frm[frmName].value = text;
As the eval
method executes the string as code, every time that it is used is a potential opening for someone to inject harmful code in the page. See cross-site scripting.
由于该eval
方法将字符串作为代码执行,因此每次使用它时都可能有人在页面中注入有害代码。请参阅跨站点脚本。
There are a few legitimate uses for the eval
function. It's however not likely that you will ever be in a situation where you actually will need it.
该eval
函数有一些合法的用途。但是,您不太可能遇到真正需要它的情况。
回答by Matt Way
This is quite an old question, and perhaps people didn't think of use cases for eval()
properly at the time. One great use for eval()
is for implementing hot reloadinginto your backend or frontend development flow.
这是一个相当古老的问题,也许当时人们没有eval()
正确考虑用例。一个很好的用途eval()
是在后端或前端开发流程中实现热重载。
Basically eval()
can make it possible for you to edit code in your editor, and have it patch your running application without it restarting, and without it losing state (depending on the implementation). You will need associated code that watches for file changes, and somehow sends the changes to your application, but eval()
is ultimately the method of converting those changes into actual js.
基本上eval()
可以让您在编辑器中编辑代码,并在不重新启动的情况下修补正在运行的应用程序,并且不会丢失状态(取决于实现)。您将需要相关代码来监视文件更改,并以某种方式将更改发送到您的应用程序,但eval()
最终是将这些更改转换为实际 js 的方法。
EDIT
编辑
Another use case I have come across:
我遇到的另一个用例:
You can use eval()
to bypass webpack's compilation process in events where you want to dynamically require files that you don't want to be transpiled (like json) For example:
你可以eval()
在你想动态地要求你不想被转译的文件(如 json)的事件中绕过 webpack 的编译过程,例如:
const data = eval('require')(`./emails/${recipient}/${type}.json`)
On that note, I think it is entirely wrong to write a statement like eval()
is evil, or should never be used. Blanket statements like these are the real evil!
在这一点上,我认为写一个类似eval()
是邪恶的或永远不应该使用的声明是完全错误的。像这样的一揽子声明是真正的邪恶!
回答by Imp
eval
makes it possible to execute (or evaluate) a string of javascript code.
eval
使执行(或评估)一串 javascript 代码成为可能。
Thus, it is applicable when you want someone to execute a string of javascript code. Like, for example, under an educational article about JavaScript, so the reader can immediately try it :)
因此,当您希望某人执行一串 javascript 代码时,它是适用的。例如,在一篇关于 JavaScript 的教育文章下,读者可以立即尝试:)
Or, again if your website is targeted to programmers, you may want them to write and execute their own plugins.
或者,如果您的网站面向程序员,您可能希望他们编写和执行自己的插件。
回答by SLaks
eval()
should not be used in Javascript.
eval()
不应在 Javascript 中使用。
eval()
used to be used to parse JSON strings, but that use has been superseded by the faster and more-secure JSON.parse
.
eval()
曾经用于解析 JSON 字符串,但这种用法已被更快、更安全的JSON.parse
.
回答by Konstantin Solomatov
The best goal of using eval is to dynamically load code, generate code at runtime and do similar meta programming stuff. In general, if you can do the same without eval, don't use eval.
使用 eval 的最佳目标是动态加载代码,在运行时生成代码并执行类似的元编程内容。一般来说,如果不用 eval 也能做同样的事情,就不要使用 eval。
回答by u283863
eval() = evil
eval() = evil
You should not really use it at all. It can be used for easy code insert, but someone can insert bad scripts using eval()
. Sometimes people use eval()
for parsing JSON, or
你根本不应该使用它。它可以用于简单的代码插入,但有人可以使用eval()
. 有时人们eval()
用于解析 JSON,或
eval("obj." + id); //newbies
but actually you can achieve all those things without using eval()
.
但实际上,您无需使用eval()
.
obj[id]; //should-do
回答by PitaJ
You can run JS that is stored in the value of a field on the webpage.
您可以运行存储在网页字段值中的 JS。
You can use eval with JS, it's just that then your code is more viable to attack. As long as it doesn't use AJAX, there's no server problem.
您可以将 eval 与 JS 一起使用,只是这样您的代码更容易受到攻击。只要不使用AJAX,就没有服务器问题。
If you use eval, you should parse out the characters [ ()<>{} ]
如果使用 eval,则应解析出字符 [ ()<>{} ]
回答by Damjan Pavlica
Maybe I am wrong, but I am using it to parse a string from a templete file:
也许我错了,但我使用它来解析模板文件中的字符串:
const name = 'Daman'
const fileContent = 'Hello ${name}'
const result = eval('`' + fileContent + '`')
Which gives me just what I need:
这给了我我需要的东西:
"Hello Daman"
回答by Swesh
As said earlier, there is a potential risk involved while using eval(), If you want to evaluate string as expression you can use ${} to evalute expression, introduced in ECMA-6
如前所述,使用 eval() 存在潜在风险,如果您想将字符串计算为表达式,您可以使用 ${} 来计算表达式,ECMA-6 中引入
回答by ykorach
To dynamically run code based on strings that represent javascript code. e.g:
根据代表javascript代码的字符串动态运行代码。例如:
let dynamicFunc = eval('(x)=>(x+2)') // or whatever plain text which is valid JS function
console.log(dynamicFunc(40));
// expected output: 42
Security warning! you should always validate these strings to avoid malicious scripts execution, especially when using it on the server side.
安全警告!您应该始终验证这些字符串以避免恶意脚本执行,尤其是在服务器端使用它时。