在 Javascript 中用 eval 替换重复出现的循环 - 好还是坏?
我的代码中的各个函数中多次出现某个循环。 为了用一个例子来说明,它几乎符合以下内容:
for (var i=0;i<= 5; i++) {
function1(function2(arr[i],i),$('div'+i));
$('span'+i).value = function3(arr[i]);
}
其中 i 当然是循环计数器。为了减少我的代码大小并避免重复循环声明,我认为我应该将其替换为以下内容:
function loop(s) {
for (var i=0;i<= 5; i++) { eval(s); }
}
[...]
loop("function1(function2(arr[i],i),$('div'+i));$('span'+i).value = function3(arr[i]);");
或者我应该?我听说过很多关于 eval() 减慢代码执行速度的说法,我希望它即使在 Nintendo DSi 浏览器中也能像适当的循环一样快,但我也想减少代码。你有什么建议?
先感谢您!
I have a certain loop occurring several times in various functions in my code.
To illustrate with an example, it's pretty much along the lines of the following:
for (var i=0;i<= 5; i++) {
function1(function2(arr[i],i),$('div'+i));
$('span'+i).value = function3(arr[i]);
}
Where i is the loop counter of course. For the sake of reducing my code size and avoid repeating the loop declaration, I thought I should replace it with the following:
function loop(s) {
for (var i=0;i<= 5; i++) { eval(s); }
}
[...]
loop("function1(function2(arr[i],i),$('div'+i));$('span'+i).value = function3(arr[i]);");
Or should I? I've heard a lot about eval() slowing code execution and I'd like it to work as fast as a proper loop even in the Nintendo DSi browser, but I'd also like to cut down on code. What would you suggest?
Thank you in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
为什么不直接将循环体放入函数中呢?
并在循环中调用它:
Why not just put the body of the loop into a function?
and call it in the loop:
嘎!
这是一个很好的问题,但是不,永远不要这样做。一般来说,不建议使用
eval
,因为您不会在加载时看到解析错误,只会在运行时看到解析错误(更难调试),更难理解作用域中的内容(更难编写) ,并且您将失去所有工具链支持(语法突出显示、脚本调试)。幸运的是,既然 Javascript 基本上是一种函数式语言,为什么不创建一个函数来封装你想要做的事情,然后调用它呢?
Gah!
This is a good question, but no, don't ever do that. Using
eval
in general is not recommended, as you won't see parse errors at load time, only at run time (harder to debug), it's harder to understand what's in scope when (harder to write), and you lose all your toolchain support (syntax highlight, script debugging).Fortunately, since Javascript is basically a functional language, why not create a function that encapsulates what you want to do, and just call that?
这是一个可怕的想法。
如果您担心带宽,请使用 缩小 和 HTTP压缩。
This is a dreadful idea.
If you are concerned about bandwidth then use minification and HTTP compression.
呃,不。
eval
应被视为接近最后的手段。 JavaScript 函数是第一类对象,所以我只需声明你需要的任何函数并传递它们作为参数之一。Uh, no.
eval
should be treated as close to a last resort. JavaScript functions are First Class Objects so I would just declare whatever functions you need and pass them as one of the params.为什么不:
Why not: