简体   繁体   English

嵌套循环 var 声明

[英]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.但是我仍然不太明白为什么如果 var 结果声明在其他地方(例如循环之外)结果完全不同。

It is not the declaration, which is hoisted for var , but the first value for each row.它不是为var提升的声明,而是每行的第一个值。

 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:可以result声明从循环中取出,如下所示:

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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