for循环中是否需要变量声明? [英] Variable declaration necessary in for loop?

查看:512
本文介绍了for循环中是否需要变量声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

两者之间有什么区别

  • for (var i=0; i<5; i++) {}
  • for (i=0; i<5; i++) {}

是否需要包含var关键字?

我知道var关键字会影响变量范围,但是我无法理解是否有必要在for循环中包含该关键字.

解决方案

在第二个示例中,您的变量是全局定义的,因此,如果您在浏览器环境中,则可以从window对象访问它. /p>

第一个等效于:

var i;
for (i=0; i<5; i++) {}

因为javascript中的所有变量都被提升到范围的开头.

What is the difference between:

  • for (var i=0; i<5; i++) {}
  • for (i=0; i<5; i++) {}

And is it necessary to include the var keyword?

I understand that the var keyword affects variable scope, but I'm having trouble understanding if it's necessary to include the keyword in for loops.

解决方案

In the second example, your variable is defined globally, so if you're in the browser environment, you can access it from the window object.

The first one is an equivalent of:

var i;
for (i=0; i<5; i++) {}

as all the variables in javascript are hoisted to the beginning of the scope.

这篇关于for循环中是否需要变量声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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