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:31

For detecting numbers, the following passage from JavaScript: The Good Parts by Douglas Crockford is relevant:

The isFinite function is the best way of determining whether a value can be used as a number because it rejects NaN and Infinity . Unfortunately, isFinite will attempt to convert its operand to a number, so it is not a good test if a value is not actually a number. You may want to define your own isNumber function:

var isNumber = function isNumber(value) { return typeof value === 'number' &&
            isFinite(value);
};
查看更多
墨雨无痕
3楼-- · 2019-01-01 12:33

or just use the invert of isNaN

if(!isNaN(data)) do something with the number else it is a string

and yes - using jQuery - $.isNumeric() is more fun for the buck.

查看更多
美炸的是我
4楼-- · 2019-01-01 12:33

This solution resolves many of the issues raised here!

This is by far the most reliable method I have used by far. I did not invent this, and cannot recall where I originally found it. But it works where other techniques fail:

// Begin public utility /getVarType/
// Returns 'Function', 'Object', 'Array',
// 'String', 'Number', 'Boolean', or 'Undefined'
getVarType = function ( data ){
  if (undefined === data ){ return 'Undefined'; }
  if (data === null ){ return 'Null'; }
  return {}.toString.call(data).slice(8, -1);
};  
// End public utility /getVarType/

Example of correctness

var str = new String();
console.warn( getVarType(str) ); // Reports "String"    
console.warn( typeof str );      // Reports "object"

var num = new Number();
console.warn( getVarType(num) ); // Reports "Number"
console.warn( typeof num );      // Reports "object"

var list = [];
console.warn( getVarType( list ) ); // Reports "Array"
console.warn( typeof list );        // Reports "object"
查看更多
刘海飞了
5楼-- · 2019-01-01 12:34

Created a jsperf on the checking if a variable is a number. Quite interesting! typeof actually has a performance use. Using typeof for anything other than numbers, generally goes a 1/3rd the speed as a variable.constructor since the majority of data types in javascript are Objects; numbers are not!

http://jsperf.com/jemiloii-fastest-method-to-check-if-type-is-a-number

typeof variable === 'number'| fastest | if you want a number, such as 5, and not '5'
typeof parseFloat(variable) === 'number'| fastest | if you want a number, such as 5, and '5'

isNaN() is slower, but not that much slower. I had high hopes for parseInt and parseFloat, however they were horribly slower.

查看更多
其实,你不懂
6楼-- · 2019-01-01 12:35

I think converting the var to a string decreases the performance, at least this test performed in the latest browsers shows so.

So if you care about performance, I would, I'd use this:

typeof str === "string" || str instanceof String

for checking if the variable is a string (even if you use var str = new String("foo"), str instanceof String would return true).

As for checking if it's a number I would go for the native: isNaN; function.

查看更多
几人难应
7楼-- · 2019-01-01 12:35

since a string as '1234' with typeof will show 'string', and the inverse cannot ever happen (typeof 123 will always be number), the best is to use a simple regex /^\-?\d+$/.test(var). Or a more advanced to match floats, integers and negative numbers, /^[\-\+]?[\d]+\.?(\d+)?$/ The important side of .test is that it WON'T throw an exception if the var isn't an string, the value can be anything.

var val, regex = /^[\-\+]?[\d]+\.?(\d+)?$/;

regex.test(val)       // false 
val = '1234';
regex.test(val)       // true
val = '-213';
regex.test(val)       // true
val = '-213.2312';
regex.test(val)       // true
val = '+213.2312';
regex.test(val)       // true
val = 123;
regex.test(val)       // true
val = new Number(123);
regex.test(val)       // true
val = new String('123');
regex.test(val)       // true
val = '1234e';
regex.test(val)       // false 
val = {};
regex.test(val)       // false 
val = false;
regex.test(val)       // false 
regex.test(undefined) // false 
regex.test(null)      // false 
regex.test(window)    // false 
regex.test(document)  // false 

If you are looking for the real type, then typeof alone will do.

查看更多
登录 后发表回答