JavaScript類型檢測

typeof

適合基本類型和函數類型,遇到null失效

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

instanceof

判斷左邊的原型鏈上是否有右邊構造函數的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()拿到,適合內置對象和基元類型,遇到null和undefined失效(IE6/7/8等返回[object Object])
[object class]是對象的類屬性,用以表達對象的類型信息

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

判斷各種類型

  // 代碼出自慕課網《JavaScript深入淺出》1-6節
  // 判斷String、Number、Boolean、undefined、null、函數、日期、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運算符可以確定出number、string、boolean、function、undefined、object這六種
  • 但object中還包括了Array、RegExp、Object、Date、Number、Boolean、String這幾種構造函數
  • 所以可以使用instanceof運算符來排除相應的類型
  • null和window使用全等運算符進行驗證
  • 為了簡化代碼,先使用instanceof來驗證部分類型,剩下的就可以直接使用typeof來驗證類型
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容