在Javascript中声明var以进行循环声明 [英] Declaring var inside Javascript for loop declaration

查看:66
本文介绍了在Javascript中声明var以进行循环声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确定我已经阅读了有关此的讨论,但找不到.简单地说,在循环的声明中声明for循环的增量是否有弊端?这有什么区别?

  function foo(){对于(var i = 0; i< 7; i ++){//代码}} 

...还有这个

  function foo(){var i;对于(i = 0; i< 7; i ++){//代码}} 

由于JS具有功能范围,所以应该没问题吧?在某些情况下,前一种方法会引起问题吗?

如果它们是相同的,那么为什么Crockford/JSLint对此全都是绝不拖欠"呢?

解决方案

这些完全相同.javascript中的所有局部变量都具有函数作用域,这意味着它们在声明它们的整个函数中都有效.起初,这通常是反直观的,因为大多数花括号语言将变量的生存期限定在声明它们的块中./p>

部分Javascript开发人员非常喜欢第二种形式.这样做的理由是,由于所有变量都具有函数作用域,因此即使对于不熟悉Javascript的用户,也应在函数级别声明它们,以使生存期明确.但这只是一种样式,绝不是硬性规定

编辑

请注意,通过引入 ES6 let ,现在您可以在循环内部使用let来获取真正的块范围变量

These are exactly the same. All local variables in javascript have function scope which means they are alive for the entire function they are declared in. This is often counter intuitive at first as most curly brace languages scope the life time of the variable to the block they are declared in.

A portion of Javascript developers very much prefer the second form. The rationale is that since all variables have function scope, you should declare them at the function level to make the life time explicit even for those not familiar with Javascript. This is just a style though and by no means a hard rule

EDIT

Note that with the introduction of ES6 let, you can now use let inside your loop for real block-scoped variable more details

for(let i = 1; i <= 5; i++) {
   setTimeout(function(){
       console.log('Value of i : ' + i);
   },100);
}

这篇关于在Javascript中声明var以进行循环声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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