【问题标题】:how to check whether a var is string or number using javascript如何使用javascript检查var是字符串还是数字
【发布时间】:2011-07-23 10:43:09
【问题描述】:

我有一个变量var number="1234",虽然这个数字是一个数值,但它在"" 之间,所以当我使用typeofNaN 检查它时,我将它作为一个字符串得到。

function test()
{
    var number="1234"

if(typeof(number)=="string")
{
    alert("string");
}
if(typeof(number)=="number")
{
    alert("number");
}

}

我总是得到alert("string"),你能告诉我如何检查这是否是一个数字吗?

【问题讨论】:

标签: javascript typeof


【解决方案1】:

据我了解您的问题是您要求进行测试 检测字符串是否代表数值。

应该是快速测试

function test() {
   var number="1234"
   return (number==Number(number))?"number":"string"
}

作为数字,如果在没有new 关键字的情况下调用,则将字符串转换为数字。 如果变量内容未被触及(== 会将数值转换回字符串) 你正在处理一个数字。否则为字符串。

function isNumeric(value) {
   return (value==Number(value))?"number":"string"
}

/* tests evaluating true */
console.log(isNumeric("1234"));  //integer
console.log(isNumeric("1.234")); // float
console.log(isNumeric("12.34e+1")); // scientific notation
console.log(isNumeric(12));     // Integer
console.log(isNumeric(12.7));   // Float
console.log(isNumeric("0x12")); // hex number

/* tests evaluating false */
console.log(isNumeric("1234e"));
console.log(isNumeric("1,234"));
console.log(isNumeric("12.34b+1"));
console.log(isNumeric("x"));

【讨论】:

  • 当值为空字符串或空格时失败,因为两者都转换为 0 和 0 == ''
【解决方案2】:

线

 var number = "1234";

创建一个值为“1234”的新字符串对象。通过将值放在引号中,您可以说它是一个字符串。

如果要检查字符串是否只包含数字,可以使用regular expressions

if (number.match(/^-?\d+$/)) {
    alert("It's a whole number!");
} else if (number.match(/^-?\d+*\.\d+$/)) {
    alert("It's a decimal number!");
}

/^\d+$/ 模式意味着:在字符串的开头 (^),有一个可选的减号 (-?),然后是一个数字 (\d),然后是任何更多的数字 (@ 987654329@),然后是字符串的结尾 ($)。另一种模式只是在数字组之间寻找一个点。

【讨论】:

【解决方案3】:

【讨论】:

【解决方案4】:

将其转换为数字,然后将其与原始字符串进行比较。

if ( parseFloat(the_string,10) == the_string ) {
    // It is a string containing a number (and only a number)
}

【讨论】:

    【解决方案5】:

    因为var number="1234" 是一个字符串。双引号使其成为文字。

    如果你想要一个数字,像这样使用它

    var number = 1234;
    

    更新:

    例如,如果你从输入标签中获取输入,数据类型将是字符串,如果你想将它转换为数字,你可以使用 parseInt() 函数

    var number = "1234";
    
    var newNumber = parseInt(number);
    
    alert(typeof newNumber); // will result in string
    

    【讨论】:

    • Ibu:绝对是的,但我的问题是我要通过一个文本框来获取“1234”,如何删除“”以使其成为一个数字。虽然当我对从文本框中获得的数据发出警报时,我得到它为 1234 但在检查时它给了我一个字符串
    • 查看我的更新@Romi,将 parseInt() 用于整数或 parseFloat() 用于十进制数将有助于解决此问题
    • 输入结尾有非数字字符时失败。
    【解决方案6】:

    另一种简单的方法:

    var num_value = +value;
    if(value !== '' && !isNaN(num_value)) {
        // the string contains (is) a number
    }
    

    【讨论】:

    • 空字符串转换为零,因此!isNaN(+('')) 给出错误。空格和 null 也转换为零,因此它们将返回 true(尽管在这种情况下 null 不是预期值)。
    • 我觉得最简单的就是:function isNumber(n) { return !isNaN(parseFloat(n)) && isFinite(n); }张贴here
    猜你喜欢
    • 2014-12-20
    • 2011-09-11
    • 2020-07-24
    • 2015-01-01
    • 2013-10-09
    • 1970-01-01
    相关资源
    最近更新 更多