问题描述
我正在尝试进行某些表单验证,出于某种原因,当我在输入字段中输入数字时,它会将typeof显示为字符串。
I am trying to preform some form validation, and for some reason when I enter a number on the input field it shows the typeof as a string.
我真的我无法绕过这个。我尝试过在线研究,但找不到答案。
I really can't wrap my head around this. I have tried researching online but couldn't find an answer.
任何帮助都会非常感激。下面是我的代码链接到jsfiddle示例。
Any help would be really appreciated. Below is my code a link to jsfiddle example.
提前谢谢
<button>Check if number</button>
<input id="number" type="number">
<script>
$("button").click(function () {
var number = $("#number").val();
alert(typeof (number));
if(typeof number !== "number"){
alert("not a number");
}
});
</script>
推荐答案
这是因为输入的值始终是串。例如,当我输入 3
时,实际值不是数字 3
,它是字符串 3
。要检查它是否不是数字,请使用 isNaN()
,这是一个Javascript本机函数,用于检查某些内容是否不是数字。例如,当您运行 isNaN(3)
时,它将返回 false
,因为 3
是一个数字。
This is because the value of an input is always a string. For example, when I'm entering 3
, the actual value is not the number 3
, it is the string "3"
. To check if it is not a number, use isNaN()
, a Javascript native function to check if something is not a number. For example, when you run isNaN("3")
it will return false
, since 3
is a number.
这篇关于为什么javascript将typeof显示为“string”?什么时候?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!