JavaScript有五种数据判断类型方法:
- typeof
- instanceof
- constructor
- Object.prototype.toString.call()
- jquery.type()
一、typeof方法:
1、可以判断数据类型,它返回表示数据类型的字符串(返回结果只能包括number,boolean,string,function,object,undefined);
2、可以使用typeof判断变量是否存在(如if(typeof a!=“undefined”){…});
3、Typeof 运算符的问题是无论引用的对象是什么类型 它都返回object
例如:
console.log(
typeof 100, //"number"
typeof 'abc', //"string"
typeof false, //"boolean"
typeof undefined, //"undefined"
typeof null, //"object"
typeof [1,2,3], //"object"
typeof {
a:1,b:2,c:3}, //"object"
typeof function(){
console.log('aaa');}, //"function"
typeof new Date(), //"object"
typeof /^[a-zA-Z]{
5,20}$/, //"object"
typeof new Error() //"object"
typeof new Number(100), //'object'
typeof new String('abc'),// 'string'
typeof new Boolean(true),//'boolean'
)
二、instanceof方法:
一般用来检测引用数据类型,表达式为:A instan