I have problems with check prompt data. I need to check, if the prompt data will be string, paragraph could show that data is not number. But according to my code, when I enter string data, it shows me odd or even message, but not 'Not number'. What's can be wrong? Thanks a lot!
prompt()
always returns a string , use parseInt(prompt(), 10)
to convert it to a string (10 is the numeric base, eg.: 2 means its a binary number)
It will return either a number or a NaN
( N ot A N umber) value.
typeof(NaN) === 'number'
NaN === NaN
will result in false, use Number.isNaN
to check if the value of a variable is NaN
if (!(a === b))
is the same as if (a !== b)
Please, next time post your code as text instead of a sharing print screen of it, so we can ctrl+c, ctrl+v it
Because your second if condition evaluates as:
!("nonsense" % 2 === 0)
!(NaN % 2 === 0)
!(NaN === 0)
!(false)
true
therefore it will always show Odd" for non numbers. Maybe you should validate your data before you use it. Additionally val
will always be of type "string", you might want to parse it properly:
const num = parseInt(prompt("A number?"), 10);
if(isNaN(num)) {
//...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.