scope of javascript variables

When writing javascript code before, I found that intellij IDEA always prompts repeated variable definition warnings. After checking it, I found that the original javascript variable scope is not the same as the java that I usually use. In javascript, there is no block (code block) scope of variables, all variable definitions are function level, when you define a variable like the following code:

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

In fact, in the upper and lower for loops, the variable i is the same variable. Each time it is redefined, it will overwrite the previously defined variable. Therefore, the correct way to write it should be:

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
}

 

Reference: http://stackoverflow.com/questions/10801747/dealing-with-duplicate-declaration-warning-for-loop-variables

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326930078&siteId=291194637