在JavaScript中使用eval()的主要好处是什么? [英] What's the main benefit of using eval() in JavaScript?
问题描述
我知道这可能是一个新手问题,但是我对eval()
的主要好处感到好奇-最好在哪里使用它?我感谢任何信息.
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
函数:永不.
其目的是将字符串评估为Javascript表达式.示例:
It's purpose is to evaluate a string as a Javascript expression. Example:
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;
由于eval
方法将字符串作为代码执行,因此每次使用该字符串都可能使某人有可能在页面中注入有害代码.请参阅跨站点脚本.
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.
这篇关于在JavaScript中使用eval()的主要好处是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!