Check whether variable is number or string in Java

2019-01-01 11:57发布

Does anyone know how can I check whether a variable is a number or a string in JavaScript?

28条回答
刘海飞了
2楼-- · 2019-01-01 12:35

Very late to the party; however, the following has always worked well for me when I want to check whether some input is either a string or a number in one shot.

return !!Object.prototype.toString.call(input).match(/\[object (String|Number)\]/);
查看更多
春风洒进眼中
3楼-- · 2019-01-01 12:37

Try this,

<script>
var regInteger = /^\d+$/;

function isInteger( str ) {    
    return regInteger.test( str );
}

if(isInteger("1a11")) {
   console.log( 'Integer' );
} else {
   console.log( 'Non Integer' );
}
</script>
查看更多
听够珍惜
4楼-- · 2019-01-01 12:37

jQuery uses this:

function isNumber(obj) {
  return !isNaN( parseFloat( obj ) ) && isFinite( obj );
}
查看更多
有味是清欢
5楼-- · 2019-01-01 12:39

The best way I have found is to either check for a method on the string, i.e.:

if (x.substring) {
// do string thing
} else{
// do other thing
}

or if you want to do something with the number check for a number property,

if (x.toFixed) {
// do number thing
} else {
// do other thing
}

This is sort of like "duck typing", it's up to you which way makes the most sense. I don't have enough karma to comment, but typeof fails for boxed strings and numbers, i.e.:

alert(typeof new String('Hello World'));
alert(typeof new Number(5));

will alert "object".

查看更多
与君花间醉酒
6楼-- · 2019-01-01 12:41

You're looking for isNaN():

console.log(!isNaN(123));
console.log(!isNaN(-1.23));
console.log(!isNaN(5-2));
console.log(!isNaN(0));
console.log(!isNaN("0"));
console.log(!isNaN("2"));
console.log(!isNaN("Hello"));
console.log(!isNaN("2005/12/12"));

See JavaScript isNaN() Function at MDN.

查看更多
高级女魔头
7楼-- · 2019-01-01 12:41

Can you just divide it by 1?

I assume the issue would be a string input like: "123ABG"

var Check = "123ABG"

if(Check == Check / 1)
{
alert("This IS a number \n")
}

else
{
alert("This is NOT a number \n")
}

Just a way I did it recently.

查看更多
登录 后发表回答