【问题标题】:Check that variable is a number检查变量是否为数字
【发布时间】:2009-08-29 22:48:26
【问题描述】:

如何检查变量是数字,整数还是字符串数字?

在 PHP 中我可以做到:

if (is_int($var)) {
    echo '$var is integer';
}

或者:

if (is_numeric($var)) {
    echo '$var is numeric';
}

如何在 jQuery/JavaScript 中做到这一点?

【问题讨论】:

  • 我假设您正试图避免往返于您的服务器进行测试?那将是脑死简单的方法;)

标签: javascript jquery


【解决方案1】:

javascript 函数isNaN(variable) 应该可以解决问题。如果数据不是数字,则返回 true。

【讨论】:

  • 这是个好建议。 FWIW,这是因为字符串被隐式转换为数字 - 显式代码是:isNaN(new Number(variable))。请注意,如果您希望将代码限制为整数,parseInt() 将返回NaN(可通过isNaN() 测试)。请注意,parseInt() 会很乐意忽略字符串末尾的非数字数字。
  • 这将接受可以转换为数字的所有内容,包括布尔值和'infinity';更好地使用isFinite(String(foo))
  • 不要使用 isNaN,它已经坏了。请参阅developer.mozilla.org/en-US/docs/JavaScript/Reference/… 并改用@Christoph 提出的解决方案。
【解决方案2】:

我会去的

isFinite(String(foo))

请参阅this answer 了解原因。如果您只想接受整数值,look here

【讨论】:

  • 注意这一点。 isFinite(null) === true
  • isFinite("100") 为真,我们想知道一个对象是一个数字对象。从我的简短测试来看,这里的解决方案 (Object.prototype.toString.call(obj) === "[object Number]") 是最好的:stackoverflow.com/questions/1303646/…
  • 还返回一个空字符串,我不会认为它是一个“数字”
  • Object.prototype.toString.call(obj) === "[object Number]" 如果传递 NaN 将返回 true
  • 不处理所有变量:isFinite(String(" ")) == isFinite(String("\t")) == isFinite(String("")) == true。查看链接的答案。
【解决方案3】:

我对 javascript 还是很陌生,但似乎 typeof(blah) 可以让您检查某物是否为数字(对于字符串来说它不是真的)。知道 OP 要求提供字符串 + 数字,但我认为这可能值得为其他人记录。

例如:

function isNumeric(something){
    return typeof(something) === 'number';
}

这里是the docs

下面是 typeof 产生的一些控制台运行:

typeof(12);
"number"
typeof(null);
"object"
typeof('12');
"string"
typeof(12.3225);
"number"  

我知道的一个轻微的怪异是

typeof(NaN);
"number"

但如果没有类似的东西,它就不会是 javascript 对吧?!

【讨论】:

  • 使用typeof(something) == 'number'更好的JS风格。使用== 而不是===。保留=== 以供您真正的意思使用。
  • @AdamChalcraft 大多数 linters/程序员可能会不同意并说相反 - 除非有充分的理由不使用,否则请始终使用 ===,如果你会养成使用 == 的习惯会被某天发生的一些奇怪的事情烧死。在这种情况下,没有类型强制发生,所以无论哪种方式,这都是一个相当有争议的问题。有关该主题的教育性(也很搞笑)咆哮,请查看 James Mickens 的“Towash it all away”scholar.harvard.edu/files/mickens/files/towashitallaway.pdf
【解决方案4】:

你应该使用:

if(Number.isInteger(variable))
   alert("It is an integer");
else
   alert("It is not a integer");

您可以在以下位置找到参考: Number.isInteger()

【讨论】:

    【解决方案5】:
    function isNumeric( $probe )
    {
        return parseFloat( String( $probe ) ) == $probe;
    }
    

    【讨论】:

      【解决方案6】:

      你应该使用:

      var x = 23;
      var y = 34hhj;
      
      isNaN(x); 
      isNaN(y); 
      

      如果是字符串则返回true,如果是数字则返回false。

      【讨论】:

        【解决方案7】:

        你应该使用

        使用“if条件”检查给定值是否为数字的简单方法

        function isInteger(value)      
        {       
            num=value.trim();         
            return !(value.match(/\s/g)||num==""||isNaN(num)||(typeof(value)=='number');        
        }
        

        如果我们传递的值是一个整数,它将返回true..

        solved for     
        value=""      //false null     
        value="12"    //true only integers       
        value="a"     //false     
        value=" 12"   //false      
        value="12 "   //false         
        value=" "     //false space        
        value="$12"   //false special characters 
        value="as12"    //false
        

        【讨论】:

          【解决方案8】:

          请注意空字符串''' ' 将被isNaNisFinite 视为数字。

          【讨论】:

            【解决方案9】:

            你应该使用:$.isNumeric( i )

            jQuery.isNumeric API

            【讨论】:

              【解决方案10】:

              typeof 运算符返回一个字符串,指示未计算的操作数的类型。

              const num = 42;
              console.log(typeof num === "number"); // expected return true
              if(typeof num === "number"){
                 console.log("This is number")
              }

              更多内容......

              console.log(typeof 42);
              // expected output: "number"
              
              console.log(typeof 'blubber');
              // expected output: "string"
              
              console.log(typeof true);
              // expected output: "boolean"
              
              console.log(typeof undeclaredVariable);
              // expected output: "undefined"

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 2011-02-26
                • 2010-10-28
                • 2016-08-22
                • 1970-01-01
                • 2013-10-14
                • 2011-01-12
                • 2014-01-25
                相关资源
                最近更新 更多