Javascript for循环中的变量范围 [英] Variable scope in Javascript for loop

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

问题描述

有什么区别:

function bar()
{
  for (x=0; x< 100; x++) {}
}

function bar()
{
  var x;
  for (x=0; x< 100; x++) {}
}

如果x未在该函数之外声明,那么它不是全局变量?我总是这么想,因为我通常不会声明仅在循环中使用的一次性变量,但我想知道这是否会破坏浏览器中的可比性等。

If x wasn't declared outside of that function, and so it wasn't a global variable? I always wonder this because I generally don't declare throwaway variables which are used only in a loop, but I wonder if this might break comparability in a browser or such.

推荐答案

第一个例子将添加或修改全局变量x,如果不是所需的结果,通常要避免这种情况。

The first example will either add or modify the global variable x, which is generally to be avoided if not the desired outcome.

虽然你的第二个例子符合要求(没有副作用),但我认为看起来更好的另一个例子是

While your second example works as desired (no side effects) an alternative that looks better in my opinion would be

function bar()
{
  for (var x=0; x< 100; x++) {}
}

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

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