JS循环变量范围 [英] JS loop variable scope
问题描述
我正在尝试一些简单的JS代码。我知道我们应该使用 var
关键字在循环中声明循环变量,为循环声明以避免全局变量宣言。但是我意识到循环变量在执行循环之后也存在:
I was trying out some simple JS code. I was aware that we should use var
keyword to declare a loop variable inside the loop say for
loop to avoid global variable declaration. However I realized that the loop variable exists after the execution of the loop too:
var a = [1, 2, 3, 4, 5, 6];
for (var i = 0; i < a.length; i++)
document.write(a[i]); //123456
document.write(i); //6
这不是内联的(事实上它不需要,我知道)面向对象概念中循环的循环变量如何表现。我知道我不应该尝试将OO语言中的JavaScript与任何方面进行比较。但是,我只是猜测OO语言中的行为更好。
This is not inline (in fact it does not need to be, I know) with how loop variable of for
loop in Object Oriented concepts behaves. I know I should not try to compare the JavaScript with in OO language for any aspect. However I am just guessing that the behavior in OO languages is better.
我认为,如果我们将此代码直接放在< script>中
标签然后它实际上将循环变量添加到全局范围,这是不希望的。是这样的吗?或者我认为这是错误的方式?
I think, if we put this code in directly in <script>
tag then it actually adds the loop variable to global scope which is not desired. Is it like that? or I am thinking it wrong way?
我们可以通过创建显式函数范围来实现这种行为:
We can achieve such behavior by creating explicit function scope:
var a1 = [1, 2, 3, 4, 5, 6];
(function () {
for (var i1 = 0; i1 < a.length; i1++)
document.write(a[i1]); //123456
})();
document.write(i1); //undefined
但这是生产中遵循的标准方式吗?还有什么可以做的?
But is it the standard way / followed in production? What other things can be done?
推荐答案
我们可以通过创建显式函数范围来实现这种行为。但这是生产中遵循的标准方式吗?
We can achieve such behavior by creating explicit function scope. But is it the standard way / followed in production?
是的。函数是在JavaScript中引入新范围的唯一可能性(尽管在未来的版本中可能会改变 让
);并且 IIFEs 也在生产中大量使用。
Yes. Functions are the only possibility to introduce a new scope in JavaScript (though that might change in future versions with let
); and IIFEs are heavily used in production as well.
还可以做些什么?
What other things can be done?
要将 i
的范围限制为for-loop的块?无(更不用说让
)。但是,您几乎不需要这样做,因为没有任何东西会干扰它 - var i
仍然是您的函数的本地作用域。有时,您甚至可能希望在循环后使用 i
作为持续计数器。
To limit the scope of i
to the for-loop's block? None (let alone let
). However, you hardly will need to do that, since nothing will interfere with it - var i
is still scoped local to your function. Sometimes, you even might want to use i
after the loop as an ongoing counter.
这篇关于JS循环变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!