如果我有一对函数,这两个设置局部变量,例如,变量i
共同for
循环,一个恰巧,而其他正在运行叫,有没有命名空间混乱的危险吗?
Keep in mind that JavaScript does not have block scope, but only function scope.
In addition, if you have nested loops, there will only be one i
variable in the following example:
function myFunction() {
for (var i = 0; i < 10; i++) {
for (var i = 0; i < 10; i++) {
// code here will run 10 times instead of 100 times
}
}
// variable i is still accessible from here
}
Douglas Crockford recommends that the var
statements should be the first statements in the function body in Code Conventions for the JavaScript Programming Language :
JavaScript does not have block scope, so defining variables in blocks can confuse programmers who are experienced with other C family languages. Define all variables at the top of the function.
I think he has a point, as you can see in the following example, which will not confuse readers into thinking that the variables i
and j
are held in the scope of the for
loop blocks:
function myFunction() {
var i, j; // the scope of the variables is now very clear
for (i = 0; i < 10; i++) {
for (j = 0; j < 10; j++) {
// code here will run 100 times
}
}
}
As long as you're using var
, like this:
for(var i = 0; i < something; i++)
Then it's local and you're fine, if you don't use var
, you have a global variable on your hands, and potential issues. Also if a for
loop is nested in another, you should use a different variable name for each loop.
It will be a problem if are you referring to nested loops. Every time you enter the second for loop, the value of i (previously set in the outer for loop) will be reset.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.