【问题标题】:javascript and test for number [duplicate]javascript和测试数字[重复]
【发布时间】:2013-01-07 20:38:00
【问题描述】:

可能重复:
Is there a (built-in) way in JavaScript to check if a string is a valid number?

我在 riak map reduce 工作中使用 JS。我有一个要映射的数字,并且需要是一个数字。

如果我有一个变量:

 var wp=sfggz5341&& or var=100

if 怎么检测数字?

例如

if wp==Number:    
    OK 
else:    
    pass

【问题讨论】:

标签: javascript


【解决方案1】:

您可以使用:if (!isNaN(+wp)) 进行测试。也就是说,将“可能是数字”转换为数字(使用+ 运算符。如果不能转换,则结果为NaN。所以!isNaN(...) 表示它是一个数字。

【讨论】:

    【解决方案2】:

    尝试使用
    isNaN()

    如果值为 NaN,则此函数返回 true,否则返回 false。

    【讨论】:

      【解决方案3】:

      您可以使用!NaN(wp) 来检查字符串是否为数字。

      【讨论】:

        【解决方案4】:

        您可以使用isNaN()isNumeric()

        isNumeric() 可以使用,但在以下情况下会失败:

        // Whitespace strings:
        IsNumeric(' ') == true;
        IsNumeric('\t\t') == true;
        IsNumeric('\n\r') == true;
        
        // Number literals:
        IsNumeric(-1) == false;
        IsNumeric(0) == false;
        IsNumeric(1.1) == false;
        IsNumeric(8e5) == false;
        

        所以最好的办法是:

        function isNumber(n) {
          return !isNaN(parseFloat(n)) && isFinite(n);
        }
        

        参考:https://stackoverflow.com/a/1830844/462627

        【讨论】:

        • @sachleen 更新了答案...
        【解决方案5】:

        您可以使用typeof 运算符(详见MDN):

        var wp = "sfggz53141";
        if (typeof wp === "number") {
            // number here
        } else if (typeof wp === "string") {
            // string here
        }
        

        【讨论】:

        • 如果wp'12345'typeof wp 仍然是'string'
        • @KooiInc - 是的,因为'12345' 是一个字符串,而不是一个数字。 OP 询问它是否was 一个数字,而不是它是否可以转换成一个数字。
        猜你喜欢
        • 2017-05-26
        • 2011-07-12
        • 1970-01-01
        • 2019-05-24
        • 1970-01-01
        • 1970-01-01
        • 2018-12-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多