javasript資料類型以及如何判斷資料類型

來源:互聯網
上載者:User

標籤:code   gif   對象   rac   des   array類   rman   變數   編程   

在javascript裡面一共有
5種基本的資料類型,分別是:Number,String,Boolean,Null,Undefined
7種參考型別,分別是:Object類型,Array類型,Date類型,RegExp類型,Function類型,基本封裝類型,單體內建對象。
*注“參考型別的值(對象)是參考型別的一個執行個體。在ECMAScript中,用於將資料和功能結合在一起。它長被成為類,但這種稱呼並不恰當”[1]
其中如何判斷資料類型,當我們要判斷一個變數屬於什麼資料類型時,javascript提供了那些方式讓我們判斷呢?

以基礎資料型別 (Elementary Data Type)Number和參考型別Array類舉例 //方法1:typeof
var b = 222;var c= [1,2,3];alert(typeof b);//numberalert(typeof c);//object
View Code

//方法2 instanceof 該方法只限於參考型別使用。而且要注意大小寫

1 var b = 222;2 var c= [1,2,3];3 alert(b instanceof number);//報錯4 alert(c instanceof Array);//true5 alert(d instanceof array);//true
View Code

//方法3 constructor

1 var b = 222;2 var c= [1,2,3];3 alert(c.constructor === Array);//true4 alert(b.constructor === Number);//true 這裡應該是javascript自動把變數轉為了基本封裝類型
View Code

//方法4 prototype 要注意大小寫

1 var b = 222;2 var c= [1,2,3];3 alert(Object.prototype.toString.call(b)=== ‘[Object Number]‘);//false4 alert(Object.prototype.toString.call(c)=== ‘[Object Array]‘);//false5 alert(Object.prototype.toString.call(b) === ‘[object Array]‘) //true6 alert(Object.prototype.toString.call(c) === ‘[object Array]‘) //true
View Code

 

引用:
[1][高效能JavaScript編程].(High.Performance.JavaScript).Nicholas.C.Zakas.中英對照版

 

javasript資料類型以及如何判斷資料類型

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.