[英]How to ask a user for an input and reverse that input
// *使用提示詢問用戶數值。 // *完成詢問用戶何時輸入非數字值,空字符串或按“取消”。 // *以相反的順序返回輸入數字的數組。
// PS Zero是一個有效數字,請不要在零上停止輸入。
嘗試了一個do / while循環,但我能得到的最大數組的長度為2
let userInput
let reverseArray = []
do {
userInput = prompt('Enter a number')
reverseArray.unshift(userInput)
} while(userInput == /\d*/){
userInput = prompt('Enter a number')
reverseArray.unshift(userInput)
}
您的代碼中存在一些問題
while (userInput === /\\d*/)
嘗試將userInput與/\\d*/
string匹配,如果您打算使用它來測試數字,則需要使用test
do{} while(condition)
阻塞后沒有意義(即使你在第一次迭代后失敗,這個塊也允許你第二次提示) let userInput let reverseArray = [] do { userInput = prompt('Enter a number') if(/^\\d+$/.test(userInput)){ reverseArray.unshift(+userInput) } } while (/^\\d+$/.test(userInput)) console.log(reverseArray)
您可以簡單地使用本機方法isNaN
來檢查userInput是否為數字
有一個名為isNaN的函數,它檢查數字是否為數字。 這是參考isNaN 。 以下是同一問題的示例代碼,您可以看看。
function reverseInput() { const reverseArray = []; let number = parseInt(prompt('Enter number')); while (!isNaN(number)) { reverseArray.unshift(number); number = parseInt(prompt('Enter number')); } console.log(reverseArray); } reverseInput()
簡單的while
會做:
let userInput = prompt('Enter a number'); let reverseArray = []; while (userInput != null && !isNaN(userInput) ) { reverseArray.unshift(+userInput); userInput = prompt('Enter a number'); } console.log(reverseArray);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.