在 for 循环或 if 块中声明变量有什么问题吗? [英] Is there anything wrong with declaring your vars inside of a for loop or an if block?

查看:29
本文介绍了在 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.

这篇关于在 for 循环或 if 块中声明变量有什么问题吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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