我正在制作一個試圖在 JavaScript 中解決用戶輸入的“數字”的 AI。我不希望用戶做額外的作業只是為了看到 AI 做這件事,所以在輸入欄位中,如果用戶輸入的數字少于 5 位,JavaScript 應該在末尾添加亂數變數,直到它總共有五位數。
我在一個陳述句下使用了我曾經使用過的所有回圈if,因此如果輸入的長度小于 5(如 3),則回圈將5 - the number of digits of the input (2)使用Math.random屬性添加亂數字。這是我目前擁有的代碼:
if (input.length < 5)
do {
input = (input * 10) Math.floor(Math.random() * 9) 1;
} while (input.length < 5);
}
console.log(input)
我還使用了具有基本相同條件的forandwhile回圈(顯然已針對 if 回圈進行了修改;創建了一個變數 forinput.length使其具有相同的值)。
這是我在控制臺中得到的:
5 // Inputted number (1 digit)
52 // Inputted digit random number
如您所見,回圈只運行一次,盡管它應該再運行 3 次。我也在使用嚴格模式。我的代碼編輯器是 github.dev,我使用的是 CodeSwing 控制臺。
uj5u.com熱心網友回復:
如果輸入是一個數字,它不會有“長度”,因為它不是一個字串。
您可以像這樣實作所需的結果:
let input = 5;
let digits = 2;
while (input < 10**(digits-1)) input = ~~((input Math.random())*10);
console.log(input);
請注意,這~~是一種緊湊的做法Math.floor()
或者,沒有 while 回圈:
let input = 5, digits = 2, M = Math; L = x=>~~(M.log(x)/M.log(10)) 1;
input = ~~((input M.random())*10**(digits - L(input)));
console.log(input);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/528606.html
