循环混乱

Confusion in loops

如果我把 'let tableValue' 放在 while 循环之外,那么它会显示相同的数字 10 次,当我把它写在 while 循环然后它打印值 'n'.

的 table

这两个东西有什么区别?

function table(n) {
  let i = 1;
  let tableValue = (n * i);
  while (i <= 10) {
    console.log(tableValue);
    i++;
  }
}
table(9);

function table(n) {
  let i = 1;
  while (i <= 10) {
    let tableValue = (n * i);
    console.log(tableValue);
    i++;
  }
}
table(9);

如果你输入这一行:

let tableValue = (n * i);

在你的循环之外,就像你在第一个例子中所做的那样,然后 tableValue 被设置一次,在循环开始之前,当你记录它时,你每次都记录相同的值,因为你永远不会之后再改。

此声明不是声明 tableValue 始终是 n * i,即使 ni ] 改变。如果需要,只要任一值发生变化,就需要重新计算 tableValue。这就是您将该行放入循环中所要完成的。

计算机一次一行地执行代码,不会过多地向前或向后看。当代码更改程序的状态(例如设置变量值)时,该更改会一直存在,直到稍后再次更改。

使用:

function table(n) {
  let i = 1;
  let tableValue = (n * i); // This is 1 * 9, because it is outside the while loop ( the while loop block } don’t worry that it's inside the function, it still needs to be in the while block. I think that’s why you're getting confused.
  while (i <= 10) {
     console.log(tableValue);
     i++;
  }
}
table(9);

我在我认为需要解释的行上添加了注释。