简体   繁体   中英

Nested loops var declaration

I want to print this

1 2 3 4 5 
2 3 4 5 6 
3 4 5 6 7 
4 5 6 7 8 
5 6 7 8 9 

The code appears to look like this, after many guesses

var a=5;
for (var i = 1; i <= a; i++) {  
     var result="";
 for (var j = 1; j <= a; j++) {
    result +=(i+j - 1)+ " ";
   }
   console.log(result);
  }

But I still can't quite understand why if the var result declaration is in some other place (for example outside the loops) the result is completely different.

It is not the declaration, which is hoisted for var , but the first value for each row.

 var a = 5, result; for (var i = 1; i <= a; i++) { result = ""; for (var j = 1; j <= a; j++) { result += (i + j - 1) + " "; } console.log(result); }

You can take the declaration of result out of the loop as in:

var a = 5, result;
for (...
...

But you must clear it in each outer loop iteration or it will print an ever increasing row of repeated patterns per iteration.

Final code is:

var a = 5, result;

for (var i = 1; i <= a; i++) {
    result = ""; //Clearing happens here.
    for (var j = 1; j <= a; j++) {
        result += (i + j - 1) + " ";
    }
    console.log(result);
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM