How can I test if a value is a string or an int? [duplicate]
Possible Duplicate:
Finding Variable Type in JavaScript
How can I test if a value is a string or an int? Something like.开发者_JAVA技巧..
X = ?
if X is an Int {}
if X is a String {}
Thanks!
You can use the typeof operator:
var x = 1;
console.log(typeof x);
x = 'asdf';
console.log(typeof x);
Prints:
number
string
Here's a function that favors typeof
, but defaults to Object.prototype.toString
(which is much slower) when needed.
This way some of those unexpected values you'll get from new String('x')
or null
or /regex/
(in Chrome) are covered.
var type = (function () {
var toString = Object.prototype.toString,
typeof_res = {
'undefined': 'undefined',
'string': 'string',
'number': 'number',
'boolean': 'boolean',
'function': 'function'
},
tostring_res = {
'[object Array]': 'array',
'[object Arguments]': 'arguments',
'[object Function]': 'function',
'[object RegExp]': 'regexp',
'[object Date]': 'date',
'[object Null]': 'null',
'[object Error]': 'error',
'[object Math]': 'math',
'[object JSON]': 'json',
'[object Number]': 'number',
'[object String]': 'string',
'[object Boolean]': 'boolean',
'[object Undefined]': 'undefined'
};
return function type(x) {
var the_type = typeof_res[typeof x];
return the_type && (the_type !== 'function' || (x.apply && x.call)) ?
the_type :
tostring_res[toString.call(x)] || (x ? 'object' : 'null');
};
})();
type( new String('test') ); // string
type( function(){} ); // function
type( null ); // null
type( /regex/ ); // regexp
EDIT: I had just done a rewrite, and removed a key part of the function. Fixed.
Or for a more compact version:
var type = (function() {
var i, lc, toString = Object.prototype.toString,
typeof_res = {},
tostring_res = {},
types = 'Undefined,String,Number,Boolean,Function,Array,Arguments,RegExp,Date,Null,Error,Math,JSON'.split(',');
for (i = 0; i < types.length; i++) {
lc = types[i].toLowerCase();
if (i < 5) typeof_res[lc] = lc;
tostring_res['[object ' + types[i] + ']'] = lc;
}
return function type(x) {
var the_type = typeof_res[typeof x];
return the_type && (the_type !== 'function' || (x.apply && x.call)) ?
the_type :
tostring_res[toString.call(x)] || (x ? 'object' : 'null');
};
})();
typeof
does the trick most of the time. But if your Number
or String
is not a primitive, it will return 'object'
. Generally, that is not what you want.
var str = new String('Hello');
typeof str; // 'object'
typeof
also says that null
is an 'object'
and in WebKit, a regex is a 'function'
. I think the main advantage of typeof
is to check for a variable without throwing a ReferenceError
.
You can check a variable's constructor
property too, or use variable instanceof String
. However, both of these don't work in a multiple window
environment when using cross window
code.
The other guaranteed way of determining the type is with...
var getType = function(variable) {
return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
}
jsFiddle.
use JavaScript built in typeof
function
var s = "string",
n = 1; // number
if(typeof s == 'string'){
//do stuff for string
}
if(typeof n == 'number'){
//do stuff for number
}
Others have already talked about the typeof
operator, and use of Object.prototype.toString
, but if you want to specifically test for an int as compared to any sort of number then you can do some variation of this:
function isInt(n) {
return typeof n === "number" && n === Math.floor(n);
}
(Insert all the Object.prototype.toString
stuff if desired.)
精彩评论