JavaScript類(lèi)型檢測(cè)

typeof

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

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

instanceof

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

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()

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

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]'

判斷各種類(lèi)型

  // 代碼出自慕課網(wǎng)《JavaScript深入淺出》1-6節(jié)
  // 判斷String、Number、Boolean、undefined、null、函數(shù)、日期、window對(duì)象
  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)算符來(lái)排除相應(yīng)的類(lèi)型
  • null和window使用全等運(yùn)算符進(jìn)行驗(yàn)證
  • 為了簡(jiǎn)化代碼,先使用instanceof來(lái)驗(yàn)證部分類(lèi)型,剩下的就可以直接使用typeof來(lái)驗(yàn)證類(lèi)型
最后編輯于
?著作權(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)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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