javascript - JavaScript 中的 typeof() 函数错误

标签 javascript jquery html

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:

  1. Let expr be the result of evaluating UnaryExpression.
  2. Return ToNumber(GetValue(expr)).

关于javascript - JavaScript 中的 typeof() 函数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11807092/

相关文章:

php - 将数据ajax发送到php,不刷新整个页面,而是在同一个文件中再次执行php

javascript - 滑动接触形式 - 速度问题

javascript - 全屏背景图像仅在调整浏览器窗口大小时全屏显示

javascript - 使用 javascript/jQuery 插入新行时,如何向每个表行插入 "remove button"

JavaScript a=b=c 语句

javascript - onClick使用jsZip压缩页面上的多个图片src?

javascript - 使用 JavaScript 获取 DIV 类的值

javascript - 查看函数是否已定义的更清晰方法

javascript - Bootstrap MYSQL PHP - 发送模态内容

JavaScript:从弹出窗口获取值(外部网站)