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:18
function IsNumeric(num) {
    return ((num >=0 || num < 0)&& (parseInt(num)==num) );
}
查看更多
长期被迫恋爱
3楼-- · 2019-01-01 12:19

If you're dealing with literal notation, and not constructors, you can use typeof:.

typeof "Hello World"; // string
typeof 123;           // number

If you're creating numbers and strings via a constructor, such as var foo = new String("foo"), you should keep in mind that typeof may return object for foo.

Perhaps a more foolproof method of checking the type would be to utilize the method found in underscore.js (annotated source can be found here),

var toString = Object.prototype.toString;

_.isString = function (obj) {
  return toString.call(obj) == '[object String]';
}

This returns a boolean true for the following:

_.isString("Jonathan"); // true
_.isString(new String("Jonathan")); // true
查看更多
泪湿衣
4楼-- · 2019-01-01 12:20

@BitOfUniverse's answer is good, and I come up with a new way:

function isNum(n) {
    return !isNaN(n/0);
}

isNum('')  // false
isNum(2)   // true
isNum('2k') // false
isNum('2')  //true

I know 0 can't be dividend, but here the function works perfectly.

查看更多
心情的温度
5楼-- · 2019-01-01 12:21

uh, how about just:

function IsString(obj) {
    return obj !== undefined && obj != null && obj.toLowerCase !== undefined;
}

After further review many months later, this only guarantees obj is an object that has the method or property name toLowerCase defined. I am ashamed of my answer. Please see top-voted typeof one.

查看更多
ら面具成の殇う
6楼-- · 2019-01-01 12:22
//testing data types accurately in JavaScript (opposed to "typeof")
//from http://bonsaiden.github.com/JavaScript-Garden/
function is(type, obj) {
    var clas = Object.prototype.toString.call(obj).slice(8, -1);
    return obj !== undefined && obj !== null && clas === type;
}

//basic usage
is('String', 'test'); // true
is('Array', true); // false

Or adapt it to return an unknown type:

function realTypeOf(obj) {
    return Object.prototype.toString.call(obj).slice(8, -1);
}

//usage
realTypeOf(999); // 'Number'

May 12, 2012 Update: Full example at Javascript: A Better typeof.

查看更多
君临天下
7楼-- · 2019-01-01 12:22

Jsut an FYI, if you're using jQuery you have

$.isNumeric() 

to handle this. More details on http://api.jquery.com/jQuery.isNumeric/

查看更多
登录 后发表回答