typeof
如果使用typeof来判断数据类型的话,结果如下:
console.log(
typeof 123, //"number"
typeof 'dsfsf', //"string"
typeof false, //"boolean"
typeof [1,2,3], //"object"
typeof {a:1,b:2,c:3}, //"object"
typeof function(){console.log('aaa');}, //"function"
typeof undefined, //"undefined"
typeof null, //"object"
typeof new Date(), //"object"
typeof /^[a-zA-Z]{5,20}$/, //"object"
typeof new Error() //"object"
);
使用 typeof 检测数据类型, typeof 均返回 小写的字符串类型。
Array,Object,null,Date,RegExp,Error这几个类型都被typeof判断为object,所以如果想要判断这几种类型,就不能使用typeof了。
Number,String,Boolean,Function,undefined,如果想判断这几种类型,那就可以使用typeof。
instanceof
除了使用typeof来判断,还可以使用instanceof。instanceof运算符需要指定一个构造函数,或者说指定一个特定的类型,它用来判断这个构造函数的原型是否在给定对象的原型链上。
结果如下:
console.log(
123 instanceof Number, //false
'dsfsf' instanceof String, //false
false instanceof Boolean, //false
[1,2,3] instanceof Array, //true
{a:1,b:2,c:3} instanceof Object, //true
function(){console.log('aaa');} instanceof Function, //true
undefined instanceof Object, //false
null instanceof Object, //false
new Date() instanceof Date, //true
/^[a-zA-Z]{5,20}$/ instanceof RegExp, //true
new Error() instanceof Error //true
)
Number,String,Boolean没有检测出他们的类型,但是如果使用下面的写法则可以检测出来:
使用他们对应的构造函数
var num = new Number(123);
var str = new String('dsfsf');
var boolean = new Boolean(false);
还需要注意null和undefined都返回了false,这是因为它们的类型就是自己本身,并不是Object创建出来它们,所以返回了false。
使用toString()检测对象类型
可以通过toString() 来获取每个对象的类型。为了每个对象都能通过 Object.prototype.toString() 来检测,需要以 Function.prototype.call() 或者 Function.prototype.apply() 的形式来调用,传递要检查的对象作为第一个参数,称为thisArg。
var toString = Object.prototype.toString;
toString.call(123); //"[object Number]"
toString.call('abcdef'); //"[object String]"
toString.call(true); //"[object Boolean]"
toString.call([1, 2, 3, 4]); //"[object Array]"
toString.call({name:'wenzi', age:25}); //"[object Object]"
toString.call(function(){ console.log('this is function'); }); //"[object Function]"
toString.call(undefined); //"[object Undefined]"
toString.call(null); //"[object Null]"
toString.call(new Date()); //"[object Date]"
toString.call(/^[a-zA-Z]{5,20}$/); //"[object RegExp]"
toString.call(new Error()); //"[object Error]"
封装一个获取变量准确类型的函数
function gettype(obj) {
var type = typeof obj;
if (type !== 'object') {
// 首字母大写
type = type[0].toUpperCase()+type.slice(1);
return type;
}
//如果不是object类型的数据,直接用typeof就能判断出来
//如果是object类型数据,准确判断类型必须使用Object.prototype.toString.call(obj)的方式才能判断
// 提取类型关键字
// 方式一
// Object.prototype.toString.call(obj).replace(/^\[object (\S+)\]$/, '$1');
// 方式二
// Object.prototype.toString.call(obj).slice(8,-1);
// return Object.prototype.toString.call(obj).replace(/^\[object (\S+)\]$/, '$1');
return Object.prototype.toString.call(obj).slice(8,-1);
}
console.log( gettype({}) ); // Object
console.log( gettype('123') ); // string
console.log( gettype(123) ); // number
console.log( gettype(true) ); // boolean