在一个循环中,是重新定义一个全局变量更好,还是一遍又一遍地重新声明和重新定义一个局部变量,还是没有区别?
In a loop, is it better to redefine a global variable or to redeclare and redefine a local variable over and over, or is there no difference?
例如:
是
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;
}
当然第一个更容易输入,但是当不断地重新声明同一个变量而不是将值重新分配给全局变量时,它可能会从程序中带走 speed/performance(即使是一点点)。谢谢。
因为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
的文档详细介绍了这些差异。
第二种方法是正确的。您应该只声明一次变量。
我会像这样编写您的示例代码:
var i,inc = 1/1*PI;
for(i = 1; i<100; i++){
inc = 1/i*PI;
}
这将所有变量声明放在一个地方,这样更容易阅读代码。
如果您想使用块级作用域,请使用 let 语句,如下所示:
var i;
for(i = 1; i<100; i++){
let inc = 1/i*PI;
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let
例如:
是
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;
}
当然第一个更容易输入,但是当不断地重新声明同一个变量而不是将值重新分配给全局变量时,它可能会从程序中带走 speed/performance(即使是一点点)。谢谢。
因为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
的文档详细介绍了这些差异。
第二种方法是正确的。您应该只声明一次变量。
我会像这样编写您的示例代码:
var i,inc = 1/1*PI;
for(i = 1; i<100; i++){
inc = 1/i*PI;
}
这将所有变量声明放在一个地方,这样更容易阅读代码。
如果您想使用块级作用域,请使用 let 语句,如下所示:
var i;
for(i = 1; i<100; i++){
let inc = 1/i*PI;
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let