如果我將 'let tableValue' 放在 while 回圈之外,那么它會顯示相同的數字 10 次,當我將它寫入 while 回圈中時,它會列印值 'n' 的表。我想知道這兩個東西的區別。
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);
uj5u.com熱心網友回復:
如果你把這一行:
let tableValue = (n * i);
在你的回圈之外,就像你在第一個例子中那樣,然后tableValue在回圈開始之前設定一次,當你記錄它時,你每次都記錄相同的值,因為在那之后你永遠不會改變它。
這種說法是不是一個宣告,tableValue就是總是 n * i在任何時候,即使n和i變化。如果需要,您需要tableValue在任一值更改時重新計算。這就是您通過將該行放入回圈中來完成的作業。
計算機一次執行一行代碼,不會向前或向后看太多。當代碼更改程式的狀態時,例如設定變數值,該更改將持續存在,直到稍后再次更改。
uj5u.com熱心網友回復:
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 } dont worry that its inside the function, it still needs to be in the while block. I think thats why your getting confused.
while (i <= 10) {
console.log(tableValue);
i ;
}
}
table(9);
我已經在我認為需要解釋的行上發表評論
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/323691.html
標籤:javascript 循环 while 循环
