例如:
是
for(var i = 1; i<100; i++){
var inc = 1/i*PI;
//and so forth
}
在任何方面都比
更好或更差var inc = 1/1*PI;
for(var i = 1; i<100; i++){
inc = 1/i*PI;
}
当然,第一个更容易输入,但是当不断地重新声明相同的变量而不是向全局变量重新分配值时,它可能会降低程序的速度/性能(即使是一点点)。谢谢。
最佳答案
因为 var
hoisting ,两者绝对没有区别。而且根据文档,这没有什么区别:
For that reason, it is recommended to always declare variables at the top of their scope (the top of global code and the top of function code) so it's clear which variables are function scoped (local) and which are resolved on the scope chain.
现在,如果您使用 let
如果不使用 var
,情况就会有所不同。我认为根本不会有任何性能差异,但肯定会存在语义差异。 let
的文档详细介绍了这些差异。
关于javascript - 在循环中,是重新定义全局变量更好,还是一遍又一遍地重新声明和重新定义局部变量更好,还是没有区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41785498/