為什么我的代碼不知道 while 回圈之外的 random_num1 是什么?如何讓我的代碼知道整個回圈之外的 random_num1 是什么?
let valid_input = false;
let input;
let random_num1;
while (!valid_input) {
let input = Math.round(Number(window.prompt("What should be the maximum number to guess?")));
if (input != NaN && input > 0) {
valid_input = true;
guess_message.innerHTML = `Guess a number between 1 and ${input}`;
}
console.log(input);
let random_num1 = Math.floor(Math.random() * Number(input)) 1;
console.log(random_num1); // Here the console tells me the random number
}
console.log(random_num1); // Here the console tells me its undefined
uj5u.com熱心網友回復:
在運行時random_num1未定義。由于您的代碼是同步運行的,因此它不會等待while回圈中的定義在記錄它之前發生,即使它在它之后按順序出現。
可以閱讀有關事件回圈和變數提升的更多資訊以獲取更多背景關系。
uj5u.com熱心網友回復:
只需首先將 random_num1 初始化為 0,就應該修復它。此外,由于您使用來自用戶的直接輸入作為變數輸入并將該資訊傳遞給guess_message 上的innerHTML,因此存在安全風險。如果您要使用用戶輸入,請使用 textContent 而不是 innerHTML!
uj5u.com熱心網友回復:
您在回圈中重新定義了一個新變數。嘗試 :
random_num1 = Math.floor(Math.random()*Number(input)) 1;
uj5u.com熱心網友回復:
let valid_input = false;
let input = 0;
let random_num1 = Math.floor(Math.random() * Number(input)) 1; // initial value
let finalRandomNumber = undefined; // this will be used to hold the finalValue that you want
console.log("initial random number is", random_num1);
while (!valid_input) {
let input = Math.round(
Number(window.prompt("What should be the maximum number to guess?"))
);
if (parseInt(Number(input)) > 0) {
valid_input = true;
finalRandomNumber = random_num1;
guess_message.innerHTML = `Guess a number between 1 and ${input}`;
break;
}
console.log("input is", input);
random_num1 = Math.floor(Math.random() * Math.abs(Number(input))) 1;
console.log("current random number is", random_num1); //Here the console tells me the random number
}
console.log("final result is", finalRandomNumber); //Here the console tells me its undefined
希望這可以幫助。我添加了一些控制臺日志,您可以自己更好地除錯!
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/492523.html
標籤:javascript
