Possible Duplicate:
Is there a (built-in) way in JavaScript to check if a string is a valid number?
我有一个 HTML 格式的输入搜索栏
<form class="form-inline" action="javascript:displayResult()">
<input id="searchKey" >
<button onclick="result()" type="button" class="btn btn-warning btn ">
Go
</button>
</form>
这是 Javascript 函数
function result() {
search($('#searchKey').val());
if(typeof(searchKey)=="number") { // checking if this is a number
someFunction();
}
};
问题是,对于搜索栏的每个条目,我都会得到字符串形式的值,即使搜索栏中的值是“hello”或 9789。我用过alert(typeof(searchKey));
进行验证,它总是返回字符串类型
我试图在搜索栏中区分数字和字符串,我确信有更好的方法可以做到这一点,但我不确定为什么这不起作用
我无法使用 parseInt(),因为我需要动态区分文本和数字
最佳答案
a 的值 <input type="text">
始终是一个字符串。但是,您可以使用 parseInt
将其解析为数字。 。它将导致 NaN
如果不是数字,可以从字符串中解析出来。不要忘记您必须使用 isNaN
为此,如myNumber === NaN
不是有效的操作。
更好的是,使用 isNaN(+searchKey)
,因为一元操作数将调用 ToNumber
。但是,这将忽略空格。
<小时/>9.3.1 ToNumber Applied to the String Type
ToNumber applied to Strings applies the following grammar to the input String. If the grammar cannot interpret the String as an expansion of StringNumericLiteral, then the result of ToNumber is NaN.
[see http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf for the actual rules]
11.4.6 Unary + Operator
The unary + operator converts its operand to Number type. The production UnaryExpression : + UnaryExpression is evaluated as follows:
- Let expr be the result of evaluating UnaryExpression.
- Return ToNumber(GetValue(expr)).
关于javascript - JavaScript 中的 typeof() 函数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11807092/