JavaScript類型檢測

typeof

適合基本類型和函數(shù)類型,遇到null失效

typeof 123  // 'number'
typeof ‘string’  // 'string'
typeof false  // 'boolean'
typeof undefined  // 'undefined'
typeof null  // 'object'
typeof function(){}  // 'function'

instanceof

判斷左邊的原型鏈上是否有右邊構(gòu)造函數(shù)的prototype屬性
適合自定義對象,也可以用來檢測原生類型,在不同iframe和window之間檢測失效

function Person() {}
function Student() {}
var person = new Person
Student.prototype = new Person
var yz = new Student

person instanceof Person  // true
yz instanceof Student  // true
yz instanceof Person  // true

Object.prototype.toString.apply()

通過{}.toString()拿到,適合內(nèi)置對象和基元類型,遇到null和undefined失效(IE6/7/8等返回[object Object])
[object class]是對象的類屬性,用以表達(dá)對象的類型信息

Object.prototype.toString.apply(new Array)  // '[object Array]'
Object.prototype.toString.apply(new Date)  // '[object Date]'
Object.prototype.toString.apply(new RegExp)  // '[object Regexp]'
Object.prototype.toString.apply(function(){})  // '[object Function]'
Object.prototype.toString.apply(false)  // '[object Boolean]'
Object.prototype.toString.apply('string')  // '[object String]'
Object.prototype.toString.apply(1)  // '[object Number]'
Object.prototype.toString.apply(undefined)  // [object Undefined]'
Object.prototype.toString.apply(null)  // '[object Null]'
Object.prototype.toString.apply(window)  // '[object Window]'

判斷各種類型

  // 代碼出自慕課網(wǎng)《JavaScript深入淺出》1-6節(jié)
  // 判斷String、Number、Boolean、undefined、null、函數(shù)、日期、window對象
  function typeof(el) {
    var result
    if (el === null) {
      result = 'null'
    } else if (el instanceof Array) {
      result = 'array'
    } else if (el instanceof Date) {
      result = 'date'
    } else if (el === window) {
      result = 'window'
    } else {
      result = typeof el
    }
    return result
  }

代碼分析:

  • 使用typeof運(yùn)算符可以確定出number、string、boolean、function、undefined、object這六種
  • 但object中還包括了Array、RegExp、Object、Date、Number、Boolean、String這幾種構(gòu)造函數(shù)
  • 所以可以使用instanceof運(yùn)算符來排除相應(yīng)的類型
  • null和window使用全等運(yùn)算符進(jìn)行驗(yàn)證
  • 為了簡化代碼,先使用instanceof來驗(yàn)證部分類型,剩下的就可以直接使用typeof來驗(yàn)證類型
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲(chǔ)服務(wù)。

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

  • JavaScript 類型檢測 本文介紹JavaScript的幾種類型檢測的方法,以及其各自的適用范圍。 Java...
    paradisefj閱讀 399評論 0 0
  • 本篇介紹一下如何檢測JavaScript各種類型。 5種原始類型 對象 Function Array 屬性 5種原...
    張歆琳閱讀 636評論 0 6
  • 參考視頻:JavaScript類型檢測-慕課網(wǎng) 可以用以下5種來進(jìn)行類型檢測 typeof 適用場景: 檢測基礎(chǔ)類...
    waka閱讀 347評論 2 0
  • 1、回顧自己朋友圈分享的10篇文章或鏈接,寫下自己轉(zhuǎn)發(fā)的具體動(dòng)機(jī)是什么? 答題格式為: 標(biāo)題: 動(dòng)機(jī): 標(biāo)題: 動(dòng)...
    童53閱讀 264評論 0 3
  • 人生最大的貴人永遠(yuǎn)是自己,你決定你自己的選擇,你決定自己成為什么樣的人。 01 看到了師妹在朋友圈發(fā)的新狀態(tài):每天...
    清悠1202閱讀 1,020評論 4 28

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