在提示中检测到无效号码

Detect invalid number in 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");}
}

然而,当我在提示中输入一个词时,loadImage() 被执行。

我在控制台检查过 pr 是同一个词,当我 运行:

 parseInt("word")

在 chrome 的控制台中,结果是 NaN

但是当我运行:

parseInt("word") == NaN

结果是false

如何检测提示中输入的无效数字?

您可以使用isNaN()

isNaN(1) == false // true
isNaN("hi there") == true // true
isNaN("606") == false // true
// etc etc etc 

你可以试试isNaN查一个号码

像这样

if(!isNaN(pr)){
  // Valid number
}

你可以像这样转换你的代码

!isNaN(pr) ? loadImage(parseInt(pr)) : alert("pick a valid number");