+ 2
NaN problem
So I was working with my code doing error messages for the random number generator and I got into a problem that when the user types in a letter with an underscore,it continues to say 'Random generated number between NaN and (number)' (and vice versa) or 'Random generated number between NaN and NaN' .I wanted it to display the error message. When I got confused why it didn't worked, I made a new code about NaN (do see it). I tried NaN,Number.NaN and Number('a') for variable y,but it wasn't equal to x (Note that x=NaN).Can someone help me pls? https://code.sololearn.com/W3Dfi3H51lBh/?ref=app (My code needed to be done.) https://code.sololearn.com/W5UQgU0hPgUX/?ref=app (NaN)
2 Antworten
+ 3
NaN doesn't equal to anything, not even NaN. To test if it is not a number, you have to use the Number.isNaN function.
You can do something like this:
if (isNaN(n))
throw new Error("NaN!");
Or, if you don't want to handle errors, you can just use optional values:
n = +prompt("Enter a number") || 5;
Here, n will be 5 if the user inputs something invalid (or nothing)
(Note that if the user inputs 0, it will also be 5, since 0 is evaluated to false)
+ 3
Thanks Airree!It worked!