javascript - for 循环和迭代器变量的作用域

标签 javascript for-loop scope

我在一个很长的脚本中添加了一些新功能,其中许多变量都被缩小了(只有一个字母)。

在添加 for 循环时,我必须多次检查用于迭代的传统 i 变量是否可用。即之前未在此脚本范围内采用/定义。

我的第一个想法是像这样确定范围:

(function () {
    for (var i = 0; i < 20; ++i) {
        console.log(i);    // logs 1 to 19
    }
})()
console.log('After is: ' + typeof i); // After is: undefined 

有更好的方法吗?在这种情况下,还有哪些其他方法可以考虑?

最佳答案

修复脚本不使用单字母变量。但除此之外,请改用函数:

function repeat(fun, times) {
    // Since JavaScript is function scoped
    // `i` will not leak out of the `repeat`
    // function.  We will not be able to access
    // `i` from a higher scope in this function,
    // but, we can assume that is unnecessary.
    for (var i = 0; i <= times; i++) {
        fun(i);
    }
}

var i = "some value";
repeat(function(index) {
    console.log("Index is:", index);
    console.log("`i` remains:", i);
}, 10);
console.log("After call, `i` is:", i);

关于javascript - for 循环和迭代器变量的作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20845697/

相关文章:

javascript - 获取特定div的宽度并用作另一个div的高度?

javascript - 遍历数组并根据 lo-dash 中的条件求和一个值

linux - 需要修复小循环错误

c++ - 函数返回时变量会超出范围吗?

ruby-on-rails - 在不删除默认值 `*` 的情况下扩展 SELECT

javascript - 从 MEAN 堆栈应用程序的 Controller 中的范围变量中选择不同的值

Javascript/jquery,获取 (x,y) 处的所有 div 位置。转发触摸?

C语言: Write a program that would take 30 integers and prints the largest number and the smallest number

ios - 如何在数组中然后在 TableView 中显示来自 Firebase 的用户昵称(For 循环问题)

javascript - Jquery/Javascript 中的变量作用域