如何判斷js中的數(shù)據(jù)類型:typeof、instanceof、constructor、prototype方法比較如何判斷js中的類型呢,先舉幾個(gè)例子: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";};最常見(jiàn)的判斷方法:typeofalert(typeof a) ------------> stringalert(typeof b) ------------> numberalert(typeof c) ------------> objectalert(typeof d) ------------> objectalert(typeof e) ------------> functionalert(typeof f) ------------> function其中typeof返回的類型都是字符串形式,需注意,例如:alert(typeof a == "string")-------------> truealert(typeof a == String)---------------> false另外typeof可以判斷function的類型;在判斷除Object類型的對(duì)象時(shí)比較方便。
判斷已知對(duì)象類型的方法: instanceofalert(c instanceof Array)---------------> truealert(d instanceofDate) alert(f instanceof Function)------------> truealert(f instanceof function)------------> false注意:instanceof后面一定要是對(duì)象類型,并且大小寫(xiě)不能錯(cuò),該方法適合一些條件選擇或分支。根據(jù)對(duì)象的constructor判斷:constructoralert(c.constructor ===Array) ----------> truealert(d.constructor === Date)-----------> truealert(e.constructor ===Function) -------> true注意: constructor 在類繼承時(shí)會(huì)出錯(cuò)eg,function A(){};function B(){};A.prototype = new B(); //A繼承自Bvar aObj = new A();alert(aobj.constructor === B) ----------->true;alert(aobj.constructor === A) ----------->false;而instanceof方法不會(huì)出現(xiàn)該問(wèn)題,對(duì)象直接繼承和間接繼承的都會(huì)報(bào)true:alert(aobj instanceof B) ---------------->true;alert(aobj instanceof B) ---------------->true;言歸正傳,解決construtor的問(wèn)題通常是讓對(duì)象的constructor手動(dòng)指向自己:aobj.constructor = A;//將自己的類賦值給對(duì)象的constructor屬性alert(aobj.constructor === A) ----------->true;alert(aobj.constructor === B) ----------->false; //基類不會(huì)報(bào)true了;通用但很繁瑣的方法: prototypealert(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;大小寫(xiě)不能寫(xiě)錯(cuò),比較麻煩,但勝在通用。