基本类型的检测
一
typeof
var a = null;
typeof a //object
var =;
typeof u //undefined
二
instanceof
(1)对于引用类型可以检测 但是对于原始数据类型就不是很友好 只能检测出来一部分 只能检测出来那些通过new出来的原始数据类型
解释:instanceof 是通过原型链来识别 所以对于基本数据类型 只有通过new出来的对象才能识别
let str = 'hh'
let str2 = new String('hhh')
str instanceof String // false
str2 instanceof String // true
(2)对于引用类型还是友好的
var c = new Date();
c instanceof Object //true
var v = new RegExp();
v instanceof RegExp //true
引用类型的检测
引用类型如果还用typeof检测的话就都是object 没有办法分清楚对象数组等,因此引用类型不能用typeof。
Object.prototype.toString.call(null) 最好
1.判断基本类型:
Object.prototype.toString.call(null);//”[object Null]”
Object.prototype.toString.call(undefined);//”[object Undefined]”
Object.prototype.toString.call(“abc”);//”[object String]”
Object.prototype.toString.call(123);//”[object Number]”
Object.prototype.toString.call(true);//”[object Boolean]”
2.判断原生引用类型:
函数类型
Function fn(){console.log(“test”);}
Object.prototype.toString.call(fn);//”[object Function]”
日期类型
var date = new Date();
Object.prototype.toString.call(date);//”[object Date]”
数组类型
var arr = [1,2,3];
Object.prototype.toString.call(arr);//”[object Array]”
正则表达式
var reg = /[hbc]at/gi;
Object.prototype.toString.call(arr);//”[object RegExp]”
自定义类型
function Person(name, age) {
this.name = name;
this.age = age;
}
var person = new Person("Rose", 18);
Object.prototype.toString.call(person); //”[object Object]”