for..in和for循环之间的区别,以及计数器声明
for
循环的实现之间的差异(速度,性能,副作用...):
the difference (speed, performace, side effects, ...) between implementations of the for
loop:
之间
var i;
for(i = 0; i < length; i++){ //Do something}
// more code
和
for(var i = 0; i < length; i++){ //Do something}
// more code
和
for(i = 0; i < length; i++){ //Do something}
// more code
和之间
var e;
for( e in array){ //Do something}
// more code
和
for(var e in array){ //Do something}
// more code
和
for(e in array){ //Do something}
// more code
没有区别.
JavaScript变量仅具有函数作用域,尽管实际上您可以在for
循环的初始化部分中放置var
语句,但声明为"
JavaScript variables have only function scope, and although you can place a var
statement in the initialisation part of a for
loop in reality the declaration is "hoisted" to the top of the scope such that when your second case examples run they're treated exactly like the first cases.
编辑:由于您更新了我回答后的问题 ,因此在不使用var
关键字的情况下添加的第三个语法意味着变量e
)将被创建为全局变量-除非它已经作为全局变量存在,在这种情况下,现有变量将被覆盖.全局变量访问比本地变量访问慢.
Since you updated the question after I answered, the third syntax that you added where you don't use the var
keyword means the variable i
(or e
) will be created as a global - unless it already exists as a global in which case the existing variable will be overwritten. Global variable access is slower than local variable access.
注意:我对这个问题的解释是,它不是将for循环的标准与for..in变量进行比较,而是将不同的变量声明方法相互比较以得出for循环的标准,然后执行相同的操作再次进行for..in循环.
NOTE: my interpretation of the question is that it is not comparing a standard for loop with the for..in variant, it is just compared the different variable declaration methods with each other for a standard for loop, then doing the same again for a for..in loop.