Detect invalid number in prompt

五迷三道 提交于 2019-12-13 05:25:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!