javascript变量的作用域

之前在写javascript代码时,发现intellij IDEA老是提示重复的变量定义警告,查了一下才发现,原来javascript的变量作用域跟我一般用的java其实不太一样。在javascript中,没有block(代码块)作用域的变量,所有的变量定义都是function层级的,当你像下面的代码定义了变量时:

for (var i=0; i<100; i++) {
    // your code here
}
// some other code here
for (var i=0; i<500; i++) {
    // custom code here
}

其实上下两个for循环中,变量i都是同一个变量,每次重新定义时,都会把你之前定义的变量覆盖掉,所以,正确的写法应该是:

var i = undefined, i = undefined; // duplicate declaration which will be reduced
// to one var i = undefined;

for (i=0; i<100; i++) {
    // your code here
}
// some other code here
for (i=0; i<500; i++) {
    // custom code here
}

 

参考资料:http://stackoverflow.com/questions/10801747/dealing-with-duplicate-declaration-warning-for-loop-variables

猜你喜欢

转载自hyf1844.iteye.com/blog/2366925