Trying to Remove any non-numbers from an Array - javascript

I am trying to get user input and then put this into an array, however, if the user puts in an element that is not a number how can I remove this? I can make an error message show up however the element still goes into the array.
var input_array = [];
var number = prompt('Enter a Number');
if (isNaN(number)) {
alert("Please Enter a Number");
}
var array = input_array.push(parseInt(number));

Just place the push inside an else. Also note that push returns the new length of the array - so array will be 1 in your code.
var input_array = [];
var number = prompt('Enter a Number');
if (isNaN(number)) {
alert("Please Enter a Number");
} else {
input_array.push(parseInt(number));
}
console.log(input_array);

This is a neat way of doing it using the ternary operator. Only add the input to array if it is a number.
var input_array = [];
var number = prompt('Enter a Number');
isNaN(number) ? alert('Please Enter a number'): input_array.push(number);
Also prompt returns a string, so if you want your array to contain only numbers. Use parseInt when reading input
var number = parseInt(prompt('Enter a Number'));

Related

JS: Validate integer/user input with validation loop and prompt

I am writing a number guessing game. The guessing game starts by prompting a user for a maximum number (this is not their guess yet--it's the top range for their guess). The prompt should be in a loop with validation, making sure the max number is a (rounded) positive integer. The loop should reprompt the user if the input is 0, <0, or a non-number. I am having trouble getting the validation loop to work.
This is what I have so far, and the prompt works, but the function does not work as I need it to.
let suggestion = parseInt(prompt("Help me come up with a range from 1 to a higher number. Type in a number greater than 1."));
function get_suggestion(prompt) {
let validInput = false;
let initial_ans, input;
while(!validInput) {
input = window.prompt(prompt);
initial_ans = parseInt(input);
if(initial_ans != NaN && initial_ans > 0) {
validInput = true;
message.innerHTML = "Guess a number!"
}
}
return(initial_ans);
}

Checking if user input is a floating number

choice = input.questionFloat('\t1. Display all members\' information \n\t2. Display member information \n\t3. Add new member \n\t4. Update points earned \n\t5. Statistics\n\t6. Exit \n\t>> ');
if (choice.toString().includes('.')) {
console.log ('Please enter a valid input.');
}
choice contains the input from the user. If choice is a floating number, it will prompt the user that it is a invalid input. If there a better way of doing this instead of using .includes?
You can do that easily with JavaScript.
First take and convert to number and check if it's truthy value (non NaN) and check if it's not integer.
const num = Number('123.3')
if (num && !Number.isInteger(num)){
//float
}
Why not compare it to its value in int?
const intValue = 12
console.log(parseInt(value) !== value) // false => is an int
const floatValue = 12.1
console.log(parseInt(value) !== value) // true => is not an int

Trying to sanitize input with isNaN method, but it crashes the while loop

I am attempting to code for a project that requires me to prompt the user to input a number. I have the code set up so it accepts only numbers and operates on them, but it doesn't sanitize the input until the end. I tried using an inNaN method and a while loop to keep the code going until the user enters a real number, but when it identifies NaN, it crashes. Here's my code below:
var userMin = Number(prompt("Name a minimum number to begin your range.
Only numbers, please.")); //This is the prompt that asks for the number
var repuserMin = true; //This is the beginning of the while loop
while (repuserMin){
if (isNaN(userMin)) {
repuserMin = true; //Where the if statement glitches, JSFiddle crashes at this point
} else {repuserMin = false;}}
You need to change userMin inside of the loop, by prompting the user to update the value if their entry is not a number:
var userMin = Number(prompt("Name a minimum number to begin your range. Only numbers, please.")); //This is the prompt that asks for the number
var repuserMin = true; // Trigger the loop by default
while (repuserMin) {
if (isNaN(userMin)) {
userMin = Number(prompt("Name a minimum number to begin your range. Only numbers, please."));
} else {
repuserMin = false; // Break out of the loop
console.log('Number was entered');
}
}
Yes it will crash because you are trying to run a infinite while loop there.
You need to take the input from the user every time inside the loop.
var repuserMin = true; //This is the beginning of the while loop
var userMin;
while (repuserMin) {
userMin = Number(prompt("Name a minimum number to begin your range. Only numbers, please.")); //This is the prompt that asks for the number
if (isNaN(userMin)) {
repuserMin = true; //Where the if statement glitches, JSFiddle crashes at this point
} else {
repuserMin = false;
}
}
EDIT
You need to handle the case where the user will not enter anything.
isNaN('') --> false
while (true) {
var userMin = Number(prompt("Name a minimum number to begin your range. Only numbers, please.")); //This is the prompt that asks for the number
if (!isNaN(userMin) && userMin) {
break;
}
}

Validating a data input javascript

I have been looking to validate the data input to check whether it is a integer or a string. I looked around and saw some suggestions and typeof suggestions but nothing seems to work.
var nam = prompt("Enter name:")
person.push(nam);
var mk1 = prompt("Enter mark 1:");
var mk1 = parseInt(mk1);
mark1.push(mk1);
If you want to check whether input string is not a number try this:
if (isNaN(parseInt(name, 10)) {
//name is String
} else {
//name is Number
}
use the === operator as below
if (mk1 === parseInt(mk1 , 10))
alert("mk1 is integer")
else
alert("mk1 is not an integer. May be String")
If you don't know that the argument is a number-
function isInt(n){
return Number(n)===n && n%1===0;
}
Try this way to find input type;
if(!isNaN(parseInt(mk1)))
// for integer
else if(!isNaN(parseFloat(mk1)))
//for float
else
// String
When you prompt() the user for data, you always get a string. If you want to check, whether it actually contains just a number, you can try this:
var value = prompt('...'),
num = parseInt(value, 10);
if (num == value) {
// ... it is an integer, use `num`
} else {
// ... it's not an integer (or not *just* an integer), use `value`
}
(or use parseFloat(value) for real numbers).
It's hard to say what are you trying to do really. You seem to declare var mk1 twice, which looks a bit strange. Also, even if parseInt fails (then returns NaN [Not a Number]) you add it to mark1, which is probably not what you want. Have a look at this:
var nam = prompt("Enter name:")
person.push(nam);
var mk1 = prompt("Enter mark 1:");
mk1 = parseInt(mk1);
if (Number.isNaN(mk1) === false) {
mark1.push(mk1);
} else {
alert("mark 1 is not a number");
}
Use this function:
isNaN(parseInt(mk1))
It will return "true" if not a number, and "false" if a number

Have been scanning for NaN and getting lost

I am defining a function that takes three numbers as arguments and returns the largest of them.
Here is my code:
var instructions = alert("Choose a set of numbers to input for the computer to determine which value is the largest");
var inputOne = prompt("Please input your first desired value");
var inputTwo = prompt("Please input your second desired value");
// THIS ARRAY STORES THE VALUES OF inputOne && inputTwo
var maxInput = Math.max([inputOne, inputTwo]);
var inputThree = prompt("Please input your third desired value");
// THIS WILL COMPARE BETWEEN THE inputThree && THE MAX INPUT OF THE USERS FIRST TWO CHOICES
var maxNumber = Math.max(maxInput, inputThree);
//validate if inputs are numbers and not letters
// isNaN()
var compare = function (maxNumber, inputThree) {
if (inputThree === maxNumber) {
return alert("The result is the same!");
} else if (inputThree != maxNumber) {
return alert(maxNumber + " " + "is the larger value!");
}
}
compare(maxNumber, inputThree);
Now I'm getting a result of "NaN is the larger value!" and it's driving me crazy! I tried running console.log to see where I'm getting NaN but that didn't work at all. All that did was log NaN to the console.
I also tried taking the parameters out of Math.max( ) however was just getting:
"-infinity is the larger value!"
Can someone at least give me a hint as to why this is happening? Or explain to me further what is going on.
Math.max([inputOne, inputTwo]) should be Math.max(inputOne, inputTwo)
Why don't you just get the largest of all of them with just
var maxNumber = Math.Max(inputOne, inputTwo, inputThree);
Here:
var inputThree = prompt("Please input your third desired value");
inputThree is a String (i.e. its value has a Type of String), always. And here:
var maxNumber = Math.max(maxInput, inputThree);
maxNumber is a Number, always (because that's what Math.max returns, even though the arguments are Strings). So:
inputThree === maxNumber
is always false, because a Number is never equal to a String (see the Strict Equality Comparison Algorithm). So either convert inputThree to a Number, e.g.
+inputThree === maxNumber
or use ==.
inputThree == maxNumber

Categories