關(guān)于js的數(shù)據(jù)類型檢測(cè)(最詳細(xì)解讀)

從數(shù)據(jù)類型開(kāi)始

基本數(shù)據(jù)類型:Null,Undefined,Number,String,Boolean

引用類型:Object,Array,Date,RegExp,Function

數(shù)據(jù)類型檢測(cè)目的:區(qū)分每一種數(shù)據(jù)類型

方法一:typeof關(guān)鍵字

一般用于基本數(shù)據(jù)類型檢測(cè)

=>"number"(任何數(shù)字檢測(cè)包括NaN,Infinity等)

=>“undefined”(undefined,未聲明及未定義的變量)

=>“string”(任何字符串)

=>“boolean”(true,false)

=>"object"(null,數(shù)組,對(duì)象,實(shí)例如new Date(),new Function()仍然輸出“function”)

=>"function"(函數(shù),如Function ,Date,String)

方法二:constructor

幾乎所有函數(shù)都有一個(gè)名為prototype的屬性

prototype.constructor == 該函數(shù)

每個(gè)對(duì)象都有一個(gè)__proto__屬性,該屬性指向該對(duì)象的構(gòu)造函數(shù)的ptrototype

原型鏈實(shí)現(xiàn)如圖:(補(bǔ)充:Array,Date等引用類型createdby Function,Array.prototype.__proto__ === Object.prototype,與下圖中Foo差不多)


[].constructor => Array

{}.constructor=>Object

Object.constructor=>Function(引用類型的構(gòu)造函數(shù)由new Function生成)

Array.constructor=>Function

Function.constructor=>Function(Function也是Function的實(shí)例)

(Array,F(xiàn)unction).prototype.constructor=>Object

Object.prototype.__proto__ == null

局限性:constructor并不準(zhǔn)確,可以被改寫

function Person(){

}

function Person2(){

}

Person.prototype={

constructor:Person2

}

var person = new Person()

person.constructor == Person2 (true)

方法三:instanceof

判斷實(shí)例是否屬于某個(gè)類型

實(shí)現(xiàn)原理:

局限性

可以被改寫,詳細(xì)見(jiàn)constructor示例

只能用于引用類型的檢測(cè)

所有對(duì)象類型都是Object的實(shí)例:

演算:Array instanceof Object =>true

var O = Object.prototype;

var L = Array.__proto__;

L != O;//Array.__proto__ == Function.prototype;

L = Function.prototype.__proto__;

L == O;//true

終極方法:

Object.prototype.toString.call(value) ->找到Object原型上的toString方法,讓方法執(zhí)行

許多引用類型都重寫了toString方法,所以借用call或者apply調(diào)用原型上的方法

除了Object上的toString,其他類原型上的toString都是把當(dāng)前的數(shù)據(jù)值轉(zhuǎn)換為字符串的意思

null和undefined比較的特殊:他們所屬類Null/Undefined的原型上也有toString,只不過(guò)不讓我們用而已,不僅如此其實(shí)類的原型都給屏蔽了

HTML元素對(duì)象的toString:雖然它的原型鏈很長(zhǎng),但是在其它類的原型上都沒(méi)有toString,只有在最底層Object.prototype這上才有

使用示例:

var dataType = [{

????'[object Null]' : 'null',

? ? '[object Undefined]' : 'undefiend',

? ? '[object Boolean]' : 'boolean',

? ? '[object Number]' : 'number',

? ? '[object String]' : 'string',

? ? '[object Function]' : 'function',

? ? '[object Array]' : 'array',

? ? '[object Date]' : 'date',

? ? '[object RegExp]' : 'regexp',

? ? '[object Object]' : 'object',

? ? '[object Error]' : 'error'

}]

toString = Object.prototype.toString.call;

function type(value){

????return ?dataType[toString(value)];

}

type(1)//'number'

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容