最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

javascript中類型判斷的最佳方式

 更新時(shí)間:2022年06月21日 10:22:04   作者:小旭2021  
這篇文章介紹了javascript中類型判斷的最佳方式,文中通過示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

javascript有8種數(shù)據(jù)類型

值類型

  • Number
  • Null
  • Undefined
  • String
  • Symbol
  • Boolean
  • BigInt

引用類型

  • Object
  • Array
  • Function

判斷數(shù)據(jù)類型有以下4種判斷方法

第一種方式:   typeof

typeof null   ---> "object"

 typeof undefined  ---> "undefined"

 typeof true | false  ---> 'boolean'

 typeof 42    ---> 'number'

 typeof "42" ---> 'string'

 typeof { name : '1'} | []  ---> 'object'

 typeof Symbol    ---> 'symbol'

 typeof ()=>{}       ---> 'function'

 typeof void 0      ---> 'undefined'

第二種方式  instanceof  但是這種方式只適合判斷object類型

instanceof運(yùn)算符用來判斷一個(gè)構(gòu)造函數(shù)的prototype屬性所指向的對(duì)象是否存在另外一個(gè)要檢測(cè)對(duì)象的原型鏈上

詳細(xì)介紹請(qǐng)看這里:javascript中的instanceof運(yùn)算符

比如 :
var arr = [] ;
arr instanceof Array   ---> true
null instanceof Object ---> false
[function] instanceof Object | Function  --> true

第三種方式  Object.prototype.toString.call()   這種方式可以將全部的數(shù)據(jù)類型檢測(cè)出來 也是 推薦的方式

因?yàn)閠oString是Object的原型方法, 而 Array Function 等都是Object的實(shí)例。都重寫了toString 方法。返回的是類型的字符串

Object.prototype.toString.call(null)  --->  [object Null]

 Object.prototupe.toString.call(undefined)  ---> [object Undefined]

 Object.prototype.toString.call(123)  ---> [object Number]

 Object.prototype.toString.call(true) ---> [object Boolean]

 Object.prototype.toString.call('123') ---> [object String]

 Object.prototype.toString.call({})    ---> [object Object]

 Object.prototype.toString.call([])    ---> [object Array]

 Object.prototype.toString.call(Math) ---> [object Math]

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

 Objdec.prototype.toString.call(new Date)  ---> [object Date]

 Object.prototype.toString.call(Symbol())   ---> [object Symbol]

 第四種方式: constructor  判斷對(duì)象的構(gòu)造函。

1.  null 是js 原型鏈的起點(diǎn),沒有構(gòu)造函數(shù)

  2. undefined 沒有構(gòu)造函數(shù)

  3. [].constructor  === Array  ---> true

  4. [string].constructor === String

  5. [object].constructor === object

  6. [number].constructor === Number

  7. [symbol].constructor === Symbol

  8. [function].constructor === Function

  9. [new Date].constructor === Date

  10. [RegExp].constructor === RegExp

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論

若尔盖县| 准格尔旗| 聂拉木县| 温州市| 丹凤县| 两当县| 佳木斯市| 湘潭市| 镇平县| 济宁市| 嘉善县| 杭锦后旗| 雅江县| 永春县| 乌拉特前旗| 七台河市| 镇沅| 石门县| 门头沟区| 安溪县| 留坝县| 葫芦岛市| 蒲城县| 天峨县| 景泰县| 盖州市| 嘉祥县| 成都市| 商南县| 馆陶县| 高邮市| 剑河县| 望奎县| 温州市| 宿州市| 景德镇市| 尖扎县| 大庆市| 漳州市| 罗山县| 禹城市|