我在一个很长的脚本中添加了一些新功能,其中许多变量都被缩小了(只有一个字母)。
在添加 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/