日韩黑丝制服一区视频播放|日韩欧美人妻丝袜视频在线观看|九九影院一级蜜桃|亚洲中文在线导航|青草草视频在线观看|婷婷五月色伊人网站|日本一区二区在线|国产AV一二三四区毛片|正在播放久草视频|亚洲色图精品一区

分享

數(shù)據(jù)類(lèi)型判斷

 頭號(hào)碼甲 2020-02-15

基本數(shù)據(jù)類(lèi)型:Undefined、Null、Boolean、Number、String
復(fù)雜數(shù)據(jù)類(lèi)型 :Object ( Object 類(lèi)型、Array 類(lèi)型、Date 類(lèi)型、RegExp 類(lèi)型、Function 類(lèi)型等)
ES6新增數(shù)據(jù)類(lèi)型:Symbol

1.typeof? 返回的是一個(gè)字符串,表示對(duì)象的數(shù)據(jù)類(lèi)型,全部以小寫(xiě)表示
image.png

typeof 1 //輸出number

typeof null //輸出object

typeof {} //輸出 object

typeof [] //輸出 object

typeof (function(){}) //輸出 function

typeof undefined //輸出 undefined 

typeof '111' //輸出 string 

typeof true //輸出 boolean

typeof對(duì)于判斷基本的數(shù)據(jù)類(lèi)型很有用, 但不能識(shí)別null,都把它統(tǒng)一歸為object類(lèi)型

2. instanceof? 用來(lái)判斷 A 是否為 B 的實(shí)例,只能用來(lái)判斷引用數(shù)據(jù)類(lèi)型,?并且大小寫(xiě)不能錯(cuò)

var n= [1,2,3];

var d = new Date();

var f = function(){alert(111);};

console.log(n instanceof Array) //true

console.log(d instanceof Date) //true

console.log(f instanceof Function) //true

// console.log(f instanceof function ) //false

3.constructor? 指向?qū)ο蟮臉?gòu)造函數(shù) ——?不推薦使用

var n = [1,2,3];

var d = new Date();

var f = function(){alert(111);};

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

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

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

//注意: constructor 在類(lèi)繼承時(shí)會(huì)出錯(cuò)

4.prototype 所有數(shù)據(jù)類(lèi)型均可判斷:Object.prototype.toString.call
這是對(duì)象的一個(gè)原型擴(kuò)展函數(shù),用來(lái)更精確的區(qū)分?jǐn)?shù)據(jù)類(lèi)型。

var gettype=Object.prototype.toString

gettype.call('a') \\ 輸出 [object String]

gettype.call(1) \\ 輸出 [object Number]

gettype.call(true) \\ 輸出 [object Boolean]

gettype.call(undefined) \\ 輸出 [object Undefined]

gettype.call(null) \\ 輸出 [object Null]

gettype.call({}) \\ 輸出 [object Object]

gettype.call([]) \\ 輸出 [object Array]

gettype.call(function(){}) \\ 輸出 [object Function]

js 中還有很多類(lèi)型可以判斷,如
[object HTMLDivElement] div 對(duì)象
[object HTMLBodyElement] body 對(duì)象
[object Document](IE)
[object HTMLDocument](firefox,google)
等各種dom節(jié)點(diǎn)的判斷,這些東西在我們寫(xiě)插件的時(shí)候都會(huì)用到??梢苑庋b的方法如下:

var gettype = Object.prototype.toString
var utility = {
??isObj:function(o){
????return gettype.call(o)=="[object Object]";
??},
??isArray:function(o){
????return gettype.call(o)=="[object Array]";
??},
??isNULL:function(o){
????return gettype.call(o)=="[object Null]";
??},
??isDocument:function(){
????return gettype.call(o)=="[object Document]"|| [object HTMLDocument];
??}
}

    本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶(hù)發(fā)布,不代表本站觀(guān)點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購(gòu)買(mǎi)等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶(hù) 評(píng)論公約

    類(lèi)似文章 更多