在 for 循环或 if 块中声明变量有什么问题吗?
我经常看到的习惯:
var foo, bar;
for(var i = 0; i < 5; i++) {
foo = '' + foo + i;
}
它也被我擦掉了,但我刚刚意识到我不知道我为什么要这样做.
It's also rubbed off onto me, but I've just realized I have no idea why I do it.
这样做没有什么实际问题,但是 javascript 没有块级作用域,所以如果你在循环中声明 foo 它仍然可以在整个函数中访问.
There is no real problem with doing it, however javascript does not have block level scope, so if you declare foo inside the loop it's still accessible throughout the whole function.
如果您预先声明所有变量,则在进行缩小时有一个小优势,请考虑:
There is a small advantage when doing minification if you declare all your variables up front, consider:
// Up front
var a, b, c, aVal, bVal, cVal;
for (a = 0; a < 5; ++a) {
aVal = a;
}
for (b = 0; b < 5; ++b) {
bVal = b;
}
for (c = 0; c < 5; ++c) {
cVal = c;
}
// Inline
for (var a = 0; a < 5; ++a) {
var aVal = a;
}
for (var b = 0; b < 5; ++b) {
var bVal = b;
}
for (var c = 0; c < 5; ++c) {
var cVal = c;
}
在这种情况下,当你缩小时,你的源代码中会出现更多的var"语句.这不是什么大不了的事,但随着时间的推移,它们肯定会加起来.
In this case, when you minify there will be a lot more "var" statements appearing in your source. It's not a huge deal, but they can certainly add up over time.