js数据类型:基本型和复杂型
基本数据类型:Number、String、Boolean、null、undefined
复杂型:Object
var a = "iamstring.";
var b = 222;
var c= [1,2,3];
var d = new Date();
var e = function(){alert(111);};
var f = function(){this.name="22";};
方法一::typeof
常用语判断基本数据类型,对于数组或对象只能判断是object
alert(a) ------------> string
alert(b) ------------> number
alert(c) -------------> object
alert(d) -------------> object
alert(e) -------------> function
alert(f) -------------> function
方法二:instanceof
alert(c instanceof Array) --------> true
alert(d instanceof Date) --------> true
alert(e instanceof Function) --------> true
alert(f instanceof Function) --------> false
注意:instanceof后面必须是对象类型,并且大小写不能写错。适合条件选择和分支。
方法三:constructor
alert(c.constructor === Array) ----------> true
alert(d.constructor === Date) -----------> true
alert(e.constructor === Function) -------> true
注意: constructor 在类继承时会出错
eg,
方法四: prototype
alert(Object.prototype.toString.call(a) === ‘[object String]’) -------> true;
alert(Object.prototype.toString.call(b) === ‘[object Number]’) -------> true;
alert(Object.prototype.toString.call(c) === ‘[object Array]’) -------> true;
alert(Object.prototype.toString.call(d) === ‘[object Date]’) -------> true;
alert(Object.prototype.toString.call(e) === ‘[object Function]’) -------> true;
alert(Object.prototype.toString.call(f) === ‘[object Function]’) -------> true;
大小写不能写错,比较麻烦,但胜在通用。
总结:一般用typeof判断就行,遇到想要知道Object类型的话用instanceof或者constructor