javascript中的基礎資料型別 (Elementary Data Type)以及類型檢測的幾種方法__javascript

來源:互聯網
上載者:User

1.JS中有6種基本的資料類型,JS中的所有操作都是基於這五種基本類型得到的。
(1)Object

物件類型

(2)number

數字類型

(3)String

字串類型

(4)null

(5)underfined

(6)boolean

布爾類型:true或者為false

I)JS中的資料類型轉換(非strict 模式下)

“12”==12 // true 在非strict 模式下,字串可以向數字轉換

true==1 // true 布爾值在等號兩邊會嘗試轉換為0或者1

“1”==true //true

null==underfined //true

new Object()==new Object() //true

NaN==NaN //false

new

II)JS中的資料類型轉換(非strict 模式下)

上述中的等號均不成立

註:特別的如果為基本類型中的string或者number,在必要的情況下,可以將string或者number轉化為對象object類型,轉化不是持續的。
比如:var x=”hello” ; alert(a.length) // 5

資料類型中的隱式轉化補充:“32”+32 //轉化為string

                     "32"-32 //轉化為number
JS中的類型檢測方法

(1)通過typeof來進行類型檢測

我們先來看幾個例子:

typeof 100 —->number

typeof “hello” ——>string

typeof true —–> boolean

typeof Number ——>function

typeof new Object()——->object

typeof Object ——->function

typeof null ——–>object

typeof underfined ——–>underfined

總結:如果右邊的是基本類型,則typeof會嘗試得到最基本的類型,比如number,string等等,如果是函數名,那麼則返回function,這裡Object,Number,String,等等都可以看成函數名,如果右邊是一個基本的對象,則返回object(返回的都是小寫哦)。

註:我們發現typeof null,結果返回了object,這是一個很早之前的BUG,一直沿用至今

試用範圍:如果通過typeof來判斷類型,適用於判定基本類型,或者判斷是否為函數(function)。

2.instanceof

同樣舉例來說明:

[1,2] instanceof Array ——> true

“1,2” instanceof Array ——->false

總結:instanceof 會沿著原型鏈尋找,如果左邊對象的原型鏈上,具有右邊的對象,那麼會返回true,並且注意只用於判斷擴充的物件類型(非number,string等)

比如:1 instanceof Number —–> false

 "hell"  instanceof String  ------>string

補充:instanceof的右邊必須是函數,或者是構造器,如果不是則會報

錯,檢測的是左邊的對象的原型鏈上,是否有右邊函數的prototype。

3.Object.prototype.toString

通過對象原型上的toSting方法,同樣也可以判斷類型,我們來舉例子:

Object.prototype.toString.apply([]) ——>[object Object]

Object.prototype.toString.apply(function(){}) —->[object Function]

Object.prototype.toString.apply(Number) ——->[object Function]

Object.prototype.toString.apply(String) ——–>[object Function]

Object.prototype.toString.apply(null) ———–>[object Null]

Object.prototype.toString.apply(undefined)–>[object Undefined]

使用類型:原生對象和基本類型

此外還有
(4)constructor

(5)duck type等

相關文章

聯繫我們

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