Javascript 使用typeof函数查找输出
我在写代码。这里我有一个问题,我怎样才能解决这个问题。我有一个输入行,它需要一个字符串或一个数字。所以我需要检查输出并得到答案。我需要给出一个简单的解决方案。所以我不能使用函数或类似的东西Javascript 使用typeof函数查找输出,javascript,string,numbers,typeof,Javascript,String,Numbers,Typeof,我在写代码。这里我有一个问题,我怎样才能解决这个问题。我有一个输入行,它需要一个字符串或一个数字。所以我需要检查输出并得到答案。我需要给出一个简单的解决方案。所以我不能使用函数或类似的东西 let input = prompt('Enter your text.'); if (typeof input === "string") { alert("You have string."); } else if (typeof input === &q
let input = prompt('Enter your text.');
if (typeof input === "string") {
alert("You have string.");
} else if (typeof input === "number" && input > 30) {
alert("number more than 30");
} else if (typeof input === "number" && input < 30) {
alert("number less then 30");
}
let input=prompt('输入文本');
如果(输入类型==“字符串”){
警惕(“你有字符串。”);
}else if(输入类型==“数字”&&input>30){
警报(“数量超过30”);
}else if(输入类型==“数字”&&input<30){
警报(“数字小于30”);
}
提示符
将始终返回字符串
如果要检查字符串是否纯粹由数值组成,可以使用正则表达式:
if (/^[+-]?\d+(?:\.\d+)?$/.test(input)) {
// then it's purely numerical
const num = Number(input.trim());
// perform more operations on the number
} else {
// it's not composed of only numerical characters
}
如果您不想使用正则表达式,您可以单独使用Number
,但是您还将包括像Infinity
这样的值,这可能是不需要的,并且由于Number(“”)
给出0,您必须单独检查:
const num = Number(input);
if (input.trim().length && !Number.isNaN(num)) {
// then it's a number, use num
}
我推荐的另一种方法是。考虑使用适当的模态,例如具有输入框和提交按钮的表单。
在这种情况下,如果需要数字输入,只需执行以下操作:
<input type="number">
几周前我遇到了类似的问题,我就是这样做的:
功能测试编号(测试){
如果(isNaN(测试)==false){
log(“这是一个数字”);
}否则{
log(“这不是一个数字”);
}
}
测试编号(4);//数
testNumber(“4”)//number
testNumber(“string”)//不是一个数字
let input = prompt('Enter your text.');
if(isNaN(Number(input))){alert("You have string.")};
if (Number(input) > 30) {
alert("number more than 30");
} else if (Number(input) < 30) {
alert("number less then 30");
}
let input=prompt('输入文本');
if(isNaN(Number(input)){alert(“您有字符串”)};
如果(数字(输入)>30){
警报(“数量超过30”);
}否则如果(数字(输入)<30){
警报(“数字小于30”);
}
因此,它可以将所有字符串数字更改为数字,并使用isNaN
函数检查它们是否为数字没有regexp我怎么办?我想您可以单独使用number
,但我更喜欢正则表达式方法,因为它的算法更直观(对我而言)我不建议将prompt
存储在变量内部。@Eloi为什么不?除了someVar=prompt(…)
之外,唯一的替代方法是多次调用prompt
,这是一种完全不同的方法,OP并没有表示他们想要这种方法。OP希望每个测试有一个对话框,而不是多个。@CertainPerformance哦,我的糟糕,我忘记了一旦执行输入,提示符就会从变量中消失,TBH我从未在实际项目中使用过提示符:)这会导致空字符串被检测为数字,听起来不正确。你说得对。。。我猜在我的网站上,如果字符串是空的,这个代码就不会被执行。。。不,我从未意识到。您可以在前面用其他'if'检查它是否是字符串``