1、typeof
typeof undefined; //undefined
typeof true; //boolean
typeof 1; //number
typeof NaN; //number
typeof function(){}; //function
typeof new Object(); //object
typeof ''; //string
typeof [1,2]; //object
typeof null; //object
typeof new Number(1);//object
typeof能检测出基本数据类型
由于历史原因typeof null结果为object
在检测对象为一个复杂引用类型,例如数组和正则的时候,结果返回为object。
2、instance of
[] instanceof Array; //true
[] instanceof Object; //true
new Object() instanceof Array //false
instance of返回值为一个布尔值
instanceof 是基于原型链进行查找
只要对象的原型链存在待检测类型,都返回true.
3、Object.peototype.toString.call()
Object.prototype.toString.call(1); //[object Number]
Object.prototype.toString.call(new Number(1)); //[object Number]
Object.prototype.toString.call(''); //[object String]
Object.prototype.toString.call(true); //[object Boolean]
Object.prototype.toString.call(null); //[object Null] *IE 6,7,8会返回[object Object]
Object.prototype.toString.call(undefined); //[object Undefined]
Object.prototype.toString.call([]); //[object Array]
Object.prototype.toString.call({}); //[object Object]
Object.prototype.toString.call(/^$/); //[object RegExp]
Object.prototype.toString.call((function () {}));//[object Function]
Object.peototype.toString.call()方法是调用Object上的toString原型方法,并将this绑定到待检测对象。
4.constructor
[].constructor===Array; //true
[].constructor===Object; //false
constructor方法会指向待检测对象的构造函数。
5.duck type
当看到一只鸟走起来像鸭子、游泳起来像鸭子、叫起来也像鸭子,那么这只鸟就可以被称为鸭子