怎樣判斷js對象的類型

來源:互聯網
上載者:User

怎樣判斷js對象的類型

在編寫js程式的過程中,可能常常需要判斷一個對象的類型,例如你寫了一個函數,需要通過判斷不同的參數類型來編寫不同的代碼。

首先可能會想到typeof操作符,看下面的這個例子:

 

  <script type=text/javascript>var object = {};var b = true;alert(typeof object +   + typeof b);  </script>
得到的結果如下:

 

從上面的結果可以看到,用typeof操作符可以顯示對象的類型,那麼typeof操作符範圍null和undefined的結果會是什麼呢?

 

/*var object = {};var b = true;alert(typeof object +   + typeof b);*/alert(typeof null +   + typeof undefined)

 

typeof 操作符作用於null居然顯示”object“(這個好像不科學,我還以為會顯示”null'“),作用於undefined顯示”undefined“(這個符合我們希望的結果),所以當用typeof操作符來判斷一個對象的類型時,特別要小心,因為這個對象有可能是null。上面只是給了一部分typeof作用於這些對象的結果,下面的表列出了typeof操作符作用於Boolean, Number, String, Array, Date, RegExp, Object, Function, null, undefined的結果(有興趣的讀者可以自行測試):

從上表的結果可以看出Array, Date, RegExp顯示的都是object,為什麼不是直接的顯示對象的類型呢?這就要引出js的另外一個操作符了:instanceof操作符,這個操作符用來判斷一個對象是否為某種類型的對象,計算的值為true或者false。先來看下:

 

var now = new Date();var pattern = /^[sS]*$/;var names = ['zq', 'john'];alert((now instanceof Date) +   + (pattern instanceof RegExp) +   + (names instanceof Array));

 

很顯然通過這個instanceof是能判斷對象的類型的,但是這個只能判斷除了基本類型(包含String類型)的其它類型,他是不能判斷基本類型的。但是instanceof不是總是能正常判斷的,考慮一個架構的情形,要判斷其類型的對象是另外一個frame傳遞過來的對象,首先來看下下面的例子。

main.html

 

frame1.html

 

 

<script type=text/javascript>var names = ['riccio zhang', 'zq', 'john']; </script>

frame2.html

 

 

     <script type=text/javascript>    document.write(top.frame1.names instanceof Array:         + (top.frame1.names instanceof Array));    document.write(

);    document.write(top.frame1.names instanceof top.frame1.Array:         + (top.frame1.names instanceof top.frame1.Array));    document.write(
);    document.write(top.frame1.Array === top.frame2.Array? + (top.frame1.Array === top.frame2.Array));  </script>     

 

names對象是在frame1架構中的,此時是通過frame1架構的Array來建立的,如果把names對象拿到frame2中的Array作比較,很顯然names不是frame2中的Array的執行個體,以為frame1和frame2壓根就不是同一和Array,從第2個現實結果可以很明顯的看出names是他本身所在的frame的執行個體,從第3個輸出可以看出frame1的Array和frame2的Array是不同的。那麼遇到上面這種跨frame的比較該怎麼辦呢?我們總不能每次都拿架構對應的Array來做比較吧,有一種必須的辦法可以解決上面的問題,看下面的代碼:

 

   var toString = {}.toString;   var now = new Date();   alert(toString.call(now))

 

{}.toString表示擷取Object對象上的toString方法(這個方法時Object對象的基本方法之一),toString.call(now)表示調用toString方法。調用Date對象最原生的toString()(這個方法是Object上面的方法)方法可以顯示[object Date]類型的字串,假如是Array,則會產生[object Array]的字樣,也就是說進行上面的操作會顯示類似[object Class]的字樣,那麼我們只要判斷這個字串不就可以知道其類型了嗎?由此可以寫出如下的工具類:

tools.js

 

var tools = (function(undefined){    var class2type = {},        toString = {}.toString;        var fun = {        type: function (obj){            return obj === null || obj === undefined ?                         String(obj) : class2type[toString.call(obj)]        },        isArray: function (obj){            return fun.type(obj) === array;        },        isFunction: function (obj){            return fun.type(obj) === function;        },        each: function (arr, callback){            var i = 0,                 hasLength = arr.length ? true : false;            if(!callback || (typeof callback !== 'function') || !hasLength){                return;            }            for(i = 0; i< arr.length; i++){                if(callback.call(arr[i], i, arr[i]) === false){                        break;                }            }        }    };    fun.each(Boolean Number String Array Date RegExp Object Function.split( ), function(i, name){        class2type[[object + name +]] = name.toLowerCase();    });    return fun;})();
tools提供了type,isArray,isFunction等方法用來判斷對象的類型,根據實際的需要可以自己添加需要判斷類型的方法。type接受一個obj參數,它將對象的實際類型以小寫形式返回,比如你的需要判斷對象的類型是Array,那麼此方法將會返回array.

 

根據上面提供的工具類,再重新改寫上面的例子:

fram2.html

 

<script type=text/javascript src=tools.js></script><script type=text/javascript>document.write(top.frame1.names instanceof Array: + (top.frame1.names instanceof Array));document.write(

);document.write(top.frame1.names instanceof top.frame1.Array: + (top.frame1.names instanceof top.frame1.Array));document.write(
);document.write(top.frame1.Array === top.frame2.Array? + (top.frame1.Array === top.frame2.Array)); document.write(
);document.write(tools.isArray(top.frame1.names)? + tools.isArray(top.frame1.names)); </script>

 

至此通過上面的根據類就可以很容易的判斷對象的類型了。

注意:在IE中例如像alert這樣的元素是不能判斷的。

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.