1. typeof
主要用于判断数据是不是基本数据类型:string、number、object、undefined、boolean,但是无法判断出function(有些浏览器会出错)、array、regExp、null
console.log(typeof '');//string console.log(typeof []);//object console.log(typeof {});//object console.log(typeof 1);//number console.log(typeof null);//object console.log(typeof undefined);//undefined console.log(typeof true);//boolean console.log(typeof function(){});//function console.log(typeof /\d/);//object
2. instanceof
主要的目的是用来检测引用类型,判断Array和RegExp,无法准确判断Function
console.log([] instanceof Array);//true console.log({} instanceof Object);//true console.log(/\d/ instanceof RegExp);//true console.log(function(){} instanceof Object);//true console.log(function(){} instanceof Function);//true console.log('' instanceof String);//false console.log(1 instanceof Number);//false
3. Object.prototype.toString
对象的一个原生原型扩展函数,用来精确的区分数据类型
Object.prototype.toString.call(data).slice(8,-1) === 'Array' var type=Object.prototype.toString; console.log(type.call(''));//[object String] console.log(type.call([]));//[object Array] console.log(type.call({}));//[object Object] console.log(type.call(false));//[object Boolean] console.log(type.call(null));//[object Null] console.log(type.call(undefined));//[object Undefined] console.log(type.call(function(){}));//[object Function]