第一种 typeof
一般主要用来检测基本数据类型,因为它检测引用数据类型返回的都是object
console.log(typeof "langshen"); // String
console.log(typeof 666); // Number
console.log(typeof true); // Boolean
console.log(typeof false); // Boolean
console.log(typeof function(){}); // Function
console.log(typeof undefined); // Undefined
console.log(typeof null); // Object
console.log(typeof []); // Object
console.log(typeof {}); // Object
typeof局限性:当 typeof 检测基本数据类型(Number、String、Boolean 、Undefined、Null)的时候是没有问题的。
但是检测引用型数据类型(Array、Object、RegExp等)的时候全都是 Object。
第二种 instanceof
这个方法主要是用来准确地检测引用数据类型(不能用来检测基本数据类型)
console.log("langshen" instanceof String); //false
console.log(666 instanceof Number); //false
console.log(true instanceof Boolean); //false
console.log(null instanceof Null);
console.log(undefined instanceof Undefined);
console.log([] instanceof Array); //true
console.log(function(){} instanceof Function); //true
console.log({} instanceof Object); //true
前三个都是以对象字面量创建的基本数据类型,但是却不是所属类的实例,只有实例方式创建出来的才是标准的对象数据类型值
instanceof是一个操作符,返回值是一个布尔值
instanceof是检测引用数据类型,而不能检测基本数据类型
第三种、constructor
constructor这个属性存在于构造函数的原型上,指向构造函数,对象可以通过 proto 在其所属类的原型上找到这个属性
console.log(("1").constructor === String); //true
console.log((1).constructor === Number); //true
console.log((true).constructor === Boolean); //true
console.log(([]).constructor === Array); //true
console.log((function() {}).constructor === Function); //true
console.log(({}).constructor === Object); //true
第四种 Object.prototype.toString.call()
可以用来准确地检测所有数据类型(最好用的方法)
Object.prototype.toString.call([])
//"[object Array]"
Object.prototype.toString.call(1)
//"[object Number]"
Object.prototype.toString.call(null)
//"[object Null]"
Object.prototype.toString.call(undefined)
//"[object Undefined]"
Object.prototype.toString.call(true)
//"[object Boolean]"
Object.prototype.toString.call('111')
//"[object String]"
Object.prototype.toString.call({})
//"[object Object]"
Object.prototype.toString.call(function add(){})
//"[object Function]"