[英]Javascript templete literals not working with random number generator
我正在嘗試生成一個隨機數,然后如果用戶輸入相同的數字,他可以向前移動,否則它將生成另一個隨機數。 但是生成隨機 num (a) 的模板文字不起作用。
var a = Math.floor(Math.random()*10); // Random num generator
var userInput = alert('Enter the numbers: ${a}'); // User input
while ( userInput !== a){ // Loop
alert("Try Again!");
userInput = alert('Enter the numbers: ${a}');
};
您的代碼中有一些可以改進的地方。
a
而不是n
令人困惑。Math.floor
可以縮短為~~
。prompt
獲得用戶輸入,而不是alert
,它僅顯示一條消息。!==
運算符將您的隨機數與用戶的輸入進行比較,該輸入始終是String
形式的數字。 所以即使他們輸入了正確的數字,它也會被解釋為不正確的,因為'3'
並不嚴格等於3
。 你必須使用!=
代替。userInput
變量,因為您只用它做一件事。 只需在while
循環的條件內內聯prompt
。n
永遠不會改變,所以用const
聲明它,這樣如果你以后不小心嘗試改變它,你會得到一個錯誤來提醒你注意。`
,而不是'
。 const n = ~~(Math.random() * 10); while (prompt(`Enter the number: ${n}`);= n) { alert('Try again;'); };
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.