首頁  >  文章  >  web前端  >  js 判斷資料類型的幾種方法

js 判斷資料類型的幾種方法

高洛峰
高洛峰原創
2017-01-14 10:24:421340瀏覽

判斷js中的資料型別有幾種方法:typeof、instanceof、 constructor、 prototype、 $.type()/jquery.type(),接下來主要比較一下這幾種方法的異同。

先舉幾個例子:

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";};  

1、最常見的判斷方法: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回傳的類型都是字串形式,需要注意,例如:另外typeof 可以判斷function的型別;在判斷Object型別的物件時比較方便。 

2、判斷已知物件類型的方法: instanceof

alert(typeof a == "string") -------------> true
alert(typeof a == String) ---------------> false

   


注意:instanceof 後面一定要是物件類型,且大小寫不能錯,此方法適合某些條件選擇或分支。

3、根據物件的constructor判斷: constructor

alert(c.constructor === Array) ----------> true

alert(d.constructor === Date) ---- -------> true

alert(e.constructor === Function) -------> true

注意: constructor 在類別繼承時會出錯

eg:

alert(c instanceof Array) ---------------> true
alert(d instanceof Date)
alert(f instanceof Function) ------------> true
alert(f instanceof function) ------------> false

而instanceof方法不會出現該問題,物件直接繼承和間接繼承的都會報true:

function A(){};
function B(){};
A.prototype = new B(); //A继承自B
var aObj = new A();
alert(aobj.constructor === B) -----------> true;
alert(aobj.constructor === A) -----------> false;

言歸正傳,解決construtor的問題通常是讓物件的constructor手動指向自己:

alert(aobj instanceof B) ----------------> true;
alert(aobj instanceof B) ----------------> true;

4、通用但很繁瑣的方法: prototype

aobj.constructor = A; //将自己的类赋值给对象的constructor属性
alert(aobj.constructor === A) -----------> true;
alert(aobj.constructor === B) -----------> false; //基类不会报true了;

大小寫不能寫錯,比較麻煩,但勝在通用。

5、無敵萬能的方法:jquery.type()

如果物件是undefined或null,則傳回對應的「undefined」或「null」。

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;

如果物件有一個內部的[[Class]]和一個瀏覽器的內建物件的 [[Class]] 相同,我們會傳回對應的 [[Class]] 名字。 (有關此技術的更多細節。)

jQuery.type( undefined ) === "undefined"
jQuery.type() === "undefined"
jQuery.type( window.notDefined ) === "undefined"
jQuery.type( null ) === "null"

其他一切都將返回它的類型“object”。

通常情況下用typeof 判斷就可以了,遇到預知Object類型的情況可以選用instanceof或constructor方法,實在沒轍就使用$.type()方法。

以上就是本文的全部內容,希望本文的內容對大家的學習或是工作能帶來一定的幫助,同時也希望多多支持PHP中文網!

更多js 判斷資料類型的幾種方法相關文章請關注PHP中文網!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn