问题
I want to get the number in a prompt
var pr = prompt("Tile size in pixels?", "150");
if(pr != null){
console.log(pr);
if (parseInt(pr) != NaN) {loadImage(parseInt(pr));}
else { alert("pick a valid number");}
}
However when I type a word in the prompt the loadImage()
is executed.
I checked in console and pr
is the same word, and when I run:
parseInt("word")
in console of chrome the result is NaN
.
But when I run:
parseInt("word") == NaN
the result is false
How to detect invalid number input in prompt?
回答1:
You can use isNaN()
isNaN(1) == false // true
isNaN("hi there") == true // true
isNaN("606") == false // true
// etc etc etc
回答2:
You can Try isNaN to check a number
like this
if(!isNaN(pr)){
// Valid number
}
you can convert your code like this
!isNaN(pr) ? loadImage(parseInt(pr)) : alert("pick a valid number");
来源:https://stackoverflow.com/questions/31148728/detect-invalid-number-in-prompt