在提示中检测到无效号码

Detect invalid number in prompt

本文关键字:无效 号码 检测 提示      更新时间:2023-09-26

我想在提示中获取数字

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控制台中,结果为CCD_ 3。

但当我跑步时:

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");