[英]how to check whether a var is string or number using javascript
我有一个变量var number="1234"
,虽然数字是一个数值,但它在""
之间,所以当我使用typeof
或NaN
检查它时,我把它作为一个字符串。
function test()
{
var number="1234"
if(typeof(number)=="string")
{
alert("string");
}
if(typeof(number)=="number")
{
alert("number");
}
}
我总是alert("string")
,你能告诉我如何检查这是否是一个数字?
据我了解您的问题,您要求进行测试以检测字符串是否代表数值。
应该进行快速测试
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"));
线
var number = "1234";
创建一个值为“1234”的新字符串 object。 通过将值放在引号中,您说它是一个字符串。
如果要检查字符串是否只包含数字,可以使用正则表达式。
if (number.match(/^-?\d+$/)) {
alert("It's a whole number!");
} else if (number.match(/^-?\d+*\.\d+$/)) {
alert("It's a decimal number!");
}
模式/^\d+$/
意味着:在字符串的开头 ( ^
),有一个可选的减号 ( -?
),然后是一个数字 ( \d
),然后是更多的数字 ( +
),然后字符串的结尾 ( $
)。 另一种模式只是在数字组之间寻找一个点。
因为var number="1234"
是一个字符串。 双引号使其成为文字。
如果你想要一个数字,像这样使用它
var number = 1234;
更新:
例如,如果您从输入标签中获取输入,则 dataType 将为字符串,如果要将其转换为数字,可以使用 parseInt() function
var number = "1234";
var newNumber = parseInt(number);
alert(typeof newNumber); // will result in string
将其转换为数字,然后将其与原始字符串进行比较。
if ( parseFloat(the_string,10) == the_string ) {
// It is a string containing a number (and only a number)
}
另一种简单的方法:
var num_value = +value;
if(value !== '' && !isNaN(num_value)) {
// the string contains (is) a number
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.