var x = 1;
console.log(typeof x);
x = 'asdf';
console.log(typeof x);
输出:
number
string
typeof
,但在需要时默认使用Object.prototype.toString
(速度较慢)。new String('x')
、null
或/regex/
(在Chrome中)等。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
编辑:我刚刚进行了重写,但删除了函数的一个关键部分。已修复。
或者更紧凑的版本:
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
大多数情况下都能胜任。但如果你的 Number
或 String
不是原始类型,它将返回 'object'
。一般来说,这不是你想要的。
var str = new String('Hello');
typeof str; // 'object'
typeof
也将null
称为'object'
,在WebKit中,一个正则表达式是一个'function'
。 我认为typeof
的主要优点是可以检查变量而不会抛出ReferenceError
异常。
您还可以检查变量的constructor
属性,或者使用variable instanceof String
。但是,在使用跨window
代码时,在多个window
环境中,这两者都无法使用。
确定类型的另一种保证方式是使用...
var getType = function(variable) {
return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
}
使用 JavaScript 内置的 typeof
函数
var s = "string",
n = 1; // number
if(typeof s == 'string'){
//do stuff for string
}
if(typeof n == 'number'){
//do stuff for number
}
其他人已经谈论了typeof
运算符和使用Object.prototype.toString
,但如果您想特别测试整数与任何类型的数字相比,则可以执行以下某种变体:
function isInt(n) {
return typeof n === "number" && n === Math.floor(n);
}
(如果需要,插入所有的Object.prototype.toString
内容。)