for..in和for循环之间的区别,以及计数器声明 [英] difference between for..in and for loops, and counter declaration

查看:95
本文介绍了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.

这篇关于for..in和for循环之间的区别,以及计数器声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆