[转载]如何判断js中的数据类型
如何判斷js中的數據類型:typeof、instanceof、 constructor、 prototype方法比較
如何判斷js中的類型呢,先舉幾個例子:
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
alert(typeof a) ? ------------> string
alert(typeof b) ? ------------> number
alert(typeof c) ? ------------> object
alert(typeof d) ? ------------> object
alert(typeof e) ? ------------> function
alert(typeof f) ? ------------> function
其中typeof返回的類型都是字符串形式,需注意,例如:
alert(typeof a == "string") -------------> true
alert(typeof a == String) ---------------> false
另外typeof 可以判斷function的類型;在判斷除Object類型的對象時比較方便。
?
判斷已知對象類型的方法: instanceof
alert(c instanceof Array) ---------------> true
alert(d instanceof Date)?
alert(f instanceof Function) ------------> true
alert(f instanceof function) ------------> false
注意:instanceof 后面一定要是對象類型,并且大小寫不能錯,該方法適合一些條件選擇或分支。
?
根據對象的constructor判斷: constructor
alert(c.constructor === Array) ----------> true
alert(d.constructor === Date) -----------> true
alert(e.constructor === Function) -------> 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了;
?
通用但很繁瑣的方法: 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方法,簡單總結下,挖個坑,歡迎補充!
轉載于:https://www.cnblogs.com/linewman/p/9918836.html
總結
以上是生活随笔為你收集整理的[转载]如何判断js中的数据类型的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 超硬核Java工程师秋招回忆录+面经汇总
- 下一篇: 2013年国家计算机一级考试试题,201
