Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ask a user for an input and reverse that input

  1. Reverse input numbers // Write the function reverseInput() that:

// * Asks the user for numeric values using prompt. // * Finishes asking when the user enters a non-numeric value, an empty string, or presses “Cancel”. // * Returns an array of the input numbers in reverse order.

// P.S. Zero is a valid number, please don’t stop the input on zero.

Tried a do/while loop but the biggest array I can get has a length of 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) 
}
like image 246
Ggd Hhdhd Avatar asked Nov 27 '25 18:11

Ggd Hhdhd


1 Answers

There are some problem in your code

  • while (userInput === /\d*/) is trying to match userInput with /\d*/ string, if you meant to use it pattern for testing digits you need to use test
  • do{} while(condition) block after while makes no sense ( this block is allowing you that second prompt even after you do while fails after first iteration )
  • You need to have a condition to avoid adding non digit to reverseArray

let userInput
let reverseArray = []
do {
  userInput = prompt('Enter a number')
  if(/^\d+$/.test(userInput)){
   reverseArray.unshift(+userInput)
  }
} while (/^\d+$/.test(userInput))

console.log(reverseArray)

You can simply use native method isNaN to check whether userInput is digit or not

like image 127
Code Maniac Avatar answered Nov 29 '25 08:11

Code Maniac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!