判断js数据类型方法
typeof:只能判断基本数据类型和function
返回的类型都是字符串形式
typeof('str') ---> "string" typeof(1) ---> "number" typeof(undefine) ---> "undefine" typeof(true) --->"boolean" typeof(null) ---> "object" typeof([]) ---> "object" typeof({}) ---> "object"
instanceof
[] instanceof Array ---> true {} instanceof Array ---> false
constructor
[].constructor === Array ---> true //注意: constructor 在类继承时会出错 eg: function A(){}; function B(){}; A.prototype = new B(); //A继承自B var aObj = new A(); alert(aobj.constructor === B) -----------> true; alert(aobj.constructor === A) -----------> false; //而instanceof方法不会出现该问题,对象直接继承和间接继承的都会报true: alert(aobj instanceof B) ----------------> true; alert(aobj instanceof B) ----------------> true; //言归正传,解决construtor的问题通常是让对象的constructor手动指向自己: aobj.constructor = A; //将自己的类赋值给对象的constructor属性 alert(aobj.constructor === A) -----------> true; alert(aobj.constructor === B) -----------> false; //基类不会报true了;
Object.prototype.toString.call() 通用
alert(Object.prototype.toString.call('') === ‘[object String]’) -------> true; alert(Object.prototype.toString.call(1) === ‘[object Number]’) -------> true; alert(Object.prototype.toString.call([]) === ‘[object Array]’) -------> true; alert(Object.prototype.toString.call(new Date) === ‘[object Date]’) -------> true; alert(Object.prototype.toString.call(f) === ‘[object Function]’) -------> true;