JavaScript 变量是在循环外还是在循环内声明?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3684923/
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
JavaScript variables declare outside or inside loop?
提问by davivid
In AS3 I believe you should initialise all variables outside loops for increased performance. Is this the case with JavaScript as well? Which is better / faster / best-practice?
在 AS3 中,我相信您应该初始化循环外的所有变量以提高性能。JavaScript 也是这种情况吗?哪个更好/更快/最佳实践?
var value = 0;
for (var i = 0; i < 100; i++)
{
value = somearray[i];
}
or
或者
for (var i = 0 ; i < 100; i++)
{
var value = somearray[i];
}
回答by bobince
There is absolutely no differencein meaning or performance, in JavaScript or ActionScript.
有绝对没有区别意义还是性能,在JavaScript或ActionScript。
varis a directive for the parser, and nota command executed at run-time. If a particular identifier has been declared varonce or more anywhere in a function body(*), then all use of that identifier in the block will be referring to the local variable. It makes no difference whether valueis declared to be varinside the loop, outside the loop, or both.
var是解析器的指令,而不是在运行时执行的命令。如果var在函数体 (*) 的任何地方已经声明了一次或多次特定标识符,则块中对该标识符的所有使用都将引用局部变量。是否value声明var在循环内、循环外或两者都没有区别。
Consequently you should write whichever you find most readable. I disagree with Crockford that putting all the vars at the top of a function is always the best thing. For the case where a variable is used temporarily in a section of code, it's better to declare varin that section, so the section stands alone and can be copy-pasted. Otherwise, copy-paste a few lines of code to a new function during refactoring, without separately picking out and moving the associated var, and you've got yourself an accidental global.
因此,您应该编写您认为最易读的内容。我不同意 Crockford 的观点,即将所有变量放在函数顶部总是最好的。对于在一段代码中临时使用变量的情况,最好var在该段中声明,这样该段是独立的,可以复制粘贴。否则,在重构期间将几行代码复制粘贴到新函数中,而无需单独挑选和移动关联的var,您就会意外获得一个全局变量。
In particular:
特别是:
for (var i; i<100; i++)
do something;
for (var i; i<100; i++)
do something else;
Crockford will recommend you remove the second var(or remove both vars and do var i;above), and jslint will whinge at you for this. But IMO it's more maintainable to keep both vars, keeping all the related code together, instead of having an extra, easily-forgotten bit of code at the top of the function.
Crockford 会建议您删除第二个var(或同时删除vars 和 dovar i;以上),并且 jslint 会为此向您发牢骚。但是 IMO 保留两个vars更易于维护,将所有相关代码保存在一起,而不是在函数顶部有一个额外的、容易忘记的代码。
Personally I tend to declare as varthe first assignment of a variable in an independent section of code, whether or not there's another separate usage of the same variable name in some other part of the same function. For me, having to declare varat all is an undesirable JS wart (it would have been better to have variables default to local); I don't see it as my duty to duplicate the limitations of [an old revision of] ANSI C in JavaScript as well.
就我个人而言,我倾向于var在独立的代码部分中声明变量的第一次赋值,无论在同一函数的其他部分是否有另一个单独使用相同的变量名。对我来说,完全必须声明var是一个不受欢迎的 JS 疣(最好让变量默认为本地);我不认为我有责任在 JavaScript 中复制 ANSI C [旧版本] 的限制。
(*: other than in nested function bodies)
(*: 嵌套函数体除外)
回答by Daniel Vassallo
In theory it shouldn't make any difference in JavaScript, since the language does not have block scope, but only function scope.
理论上它在 JavaScript 中不应该有任何区别,因为该语言没有块作用域,而只有函数作用域。
I'm not sure about the performance argument, but Douglas Crockfordstill recommends that the varstatements should be the first statements in the function body. Quoting from Code Conventions for the JavaScript Programming Language:
我不确定性能参数,但Douglas Crockford仍然建议这些var语句应该是函数体中的第一条语句。引用JavaScript 编程语言的代码约定:
JavaScript does not have block scope, so defining variables in blocks can confuse programmers who are experienced with other C family languages. Define all variables at the top of the function.
JavaScript 没有块作用域,因此在块中定义变量可能会使熟悉其他 C 系列语言的程序员感到困惑。在函数顶部定义所有变量。
I think he has a point, as you can see in the following example. Declaring the variables at the top of the function should not confuse readers into thinking that the variable iis held in the scope of the forloop block:
我认为他说的有道理,你可以在下面的例子中看到。在函数顶部声明变量不应该让读者误以为变量i保存在for循环块的范围内:
function myFunction() {
var i; // the scope of the variables is very clear
for (i = 0; i < 10; i++) {
// ...
}
}
回答by jAndy
The ECMA-/Javascriptlanguage hoistsany variable which is declared anywhere to the top of a function. That is because this language doeshave function scopeand does nothave block scopelike many other C-like languages.
That is also known as lexical scope.
该ECMA-/Javascript语言hoists被宣布为一个函数的顶部任何地方的任何变量。这是因为这种语言也有function scope和没有不具有block scope像许多其他类似C语言。
这也称为lexical scope.
If you declare something like
如果你声明类似
var foo = function(){
for(var i = 0; i < 10; i++){
}
};
This gets hoistedto:
这得到hoisted:
var foo = function(){
var i;
for(i = 0; i < 10; i++){
}
}
So it does not make any difference in performance (But correct me if I'm totally wrong here).
A much better argument for notdeclaring a variable somewhere else than at the top of a function is readability. Declaring a variable within a for-loopmight lead to the wrong assumption that this variable can only be accessed within the loop body, which is totally wrong. Infact you can access that variable anywhere within the current scope.
所以它对性能没有任何影响(但如果我在这里完全错了,请纠正我)。不在函数顶部以外的其他地方声明变量的
一个更好的论据是可读性。在 a 中声明一个变量可能会导致错误的假设,即该变量只能在循环体内访问,这是完全错误的。事实上,您可以在当前范围内的任何地方访问该变量。for-loop
回答by Aaron Digulla
Next year, all browsers will have JS engines that precompile the code so the performance difference (which comes from parsing the same block of code again and again plus executing the assignment) should become negligible.
明年,所有浏览器都将拥有 JS 引擎来预编译代码,因此性能差异(来自一遍又一遍地解析相同的代码块加上执行赋值)应该可以忽略不计。
Also, never optimize for performance unless you have to. Keeping variables close to the place where you need them the first time keeps your code clean. On the negative side, people who are used to languages with block scopes might be confused.
此外,除非必须,否则永远不要优化性能。将变量放在第一次需要它们的地方,可以保持代码整洁。不利的一面是,习惯于具有块作用域的语言的人可能会感到困惑。
回答by Matt Browne
Another consideration, now that we have letand constin ES2015, is that you can now scope variables specifically to the loop block. So unless you will need the same variable outside the loop (or if each iteration depends on an operation done to that variable in the previous iteration), it's probably preferable to do this:
另一个要考虑的,现在我们已经let和const在ES2015是,你现在可以作用域变量专门环形块。因此,除非您在循环外需要相同的变量(或者如果每次迭代都依赖于在前一次迭代中对该变量执行的操作),否则最好这样做:
for (let i = 0; i < 100; i++) {
let value = somearray[i];
//do something with `value`
}
回答by mkoistinen
I just did a simple test in Chrome. Try the fiddlein your browser and see the results
我刚刚在 Chrome 中做了一个简单的测试。在浏览器中尝试fiddle并查看结果
var count = 100000000;
var a = 0;
console.log(new Date());
for (var i=0; i<count; i++) {
a = a + 1
}
console.log(new Date());
var j;
for (j=0; j<count; j++) {
a = a + 1;
}
console.log(new Date());
var j;
for (j=0; j<count; j++) {
var x;
x = x + 1;
}
console.log(new Date());
Result is that the last test takes ~8 seconds and the previous 2 are only ~2 seconds. Very repeatably and regardless of order.
结果是最后一次测试需要约 8 秒,而前 2 次只需要约 2 秒。非常可重复且不分顺序。
So, this proves to me, that one should always declare the vars outside of the loop. Curious case to me is the first one where I declare iin the for() statement. This one appears to be just as fast as the 2nd test where I pre-declare the index.
所以,这向我证明,应该始终在循环之外声明变量。对我来说奇怪的案例是我i在 for() 语句中声明的第一个案例。这似乎与我预先声明索引的第二次测试一样快。
回答by Yan Yang
JavaScript is a language written at the bottom by C or C++, I'm not very sure which one it is. And one of its purpose is saving the lavour of handling internal memory. Even in C or C++, you won't have to worry about whether it will consume a lot of resources when variables are declared inside a loop. Why should you worry about it in JavaScript?
JavaScript 是一种由 C 或 C++ 编写的底层语言,我不太确定它是哪一种。其目的之一是节省处理内部存储器的麻烦。即使在 C 或 C++ 中,您也不必担心在循环内声明变量时是否会消耗大量资源。为什么要在 JavaScript 中担心它?
回答by Crozin
Well, that depends on what you're trying to achieve... if valuesuppose to be only a temporary variable inside loop block then it's much clearer to use second form. It's also more logical and verbose.
好吧,这取决于您要实现的目标……如果value假设只是循环块内的临时变量,那么使用第二种形式会更清楚。它也更合乎逻辑和冗长。
回答by myfavs.in
It Doesn't make difference if you declare variables inside or outside of for loop. Below is the sample code to test.
在 for 循环内部或外部声明变量没有区别。下面是要测试的示例代码。
function a() {
console.log('Function a() starts');
console.log(new Date());
var j;
for (j=0; j<100000000; j++) {
var x;
x = x + 1;
}
console.log(new Date());
console.log('Function a() Ends');
}
a()
function b() {
console.log('Function B() starts');
console.log(new Date());
var a;
var j;
for (j=0; j<100000000; j++) {
a = a + 1;
}
console.log(new Date());
console.log('Function B() Ends');
}
b()
The results showed in my case
结果显示在我的案例中
Function a() starts
VM121:3 Thu Apr 12 2018 15:20:26 GMT+0530 (India Standard Time)
VM121:9 Thu Apr 12 2018 15:20:26 GMT+0530 (India Standard Time)
VM121:10 Function a() Ends
VM121:14 Function B() starts
VM121:15 Thu Apr 12 2018 15:20:26 GMT+0530 (India Standard Time)
VM121:21 Thu Apr 12 2018 15:20:26 GMT+0530 (India Standard Time)
VM121:22 Function B() Ends
Thank you -- MyFavs.in
谢谢 - MyFavs.in
回答by Vivek Pohre
The question here is basically to declare a var inside a loop. Just think what happens if you do this:
这里的问题基本上是在循环中声明一个 var。想想如果你这样做会发生什么:
var a = 30;
var a = 50;
var a = 60;
Do you think this is right? No ... because you don't want to declare a variable so many times. When you declare a variable inside a loop isn't it declaring as many times the loop runs? Obviously it will slap you when you are in 'use strict' mode. People have disagreed with Crockford without thinking about the original question.
你认为这是对的吗?不......因为你不想多次声明一个变量。当你在循环中声明一个变量时,它是不是声明了循环运行的次数?显然,当您处于“使用严格”模式时,它会打您一巴掌。人们在没有考虑原始问题的情况下不同意克罗克福德的观点。
So it is always good to declare variables on top -- 1. For readability, 2. Making good habits.
所以在上面声明变量总是好的——1.为了可读性,2.养成良好的习惯。

