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]"