1.typeof
typeof 0; //number;
typeof true; //boolean;
typeof undefined; //undefined;
typeof "hello world" //string;
typeof function(){}; //function;
typeof null; //object
typeof {}; //object;
typeof []; //object
2.instanceof
var a={};
a instanceof Object //true
a intanceof Array //false
var b=[];
b instanceof Array //true
b instanceof Object //true
因为数组属于object中的一种,所以数组instanceof object,也是true.
var c='abc';
c instanceof String; //false
var d=new String();
d instanceof String //true
instanceof不能区分基本类型string和boolean,除非是字符串对象和布尔对象。如上例所示。
3.constructor
除了undefined和null,其他类型的变量均能使用constructor判断出类型.
区分类型,
除了对象和数组,其他用typeof去判断,
区分 数组和对象
arr.constructor==Array //true
arr.constructor==Object //false
Object.prototype.toString.call(obj) === '[object Object]' obj是对象
Object.prototype.toString.call(obj) === '[object Array]' obj是数组
4.Object.prototype.toString.call() ---------最好用
Object.prototype.toString.call(123)
//"[object Number]"
Object.prototype.toString.call('str')
//"[object String]"
Object.prototype.toString.call(true)
//"[object Boolean]"
Object.prototype.toString.call({})
//"[object Object]"
Object.prototype.toString.call([])
//"[object Array]"