js 類型與類型判斷

前言

日常積累,歡迎指正

js 數據類型

  • 基本數據類型:undefined、null、Boolean、number、string,symbol
  • 引用數據類型 :object (function)

typeof

只能判斷值類型、對象和函數
typeof 的返回值有 :

  • undefined、boolean、number、 string,symbol
  • object (null array object)
  • function

instance

a instanceOf A

本質是沿着 a 的原型鏈上是否有 A ,如果有就返回 true 否則返回 false

const arr=new Array()
arr instanceOf Array // true
arr instanceOf Object // true

constructor

原理類似於 instanceOf

value.constructor === Boolean/Number/ String/ Array/ Object/Function/Symbol

Object.prototype.toString.call(value)

可以判斷任意數據類型
這裏封裝通用方法 getType

  getType=(value)=>{
    return Object.prototype.toString.call(value).match(/\b\s\w+\b/g)[0].trim().toLowerCase();
  }

方法詳解 - 以 undefined 類型判斷爲例

  • Object.prototype.toString.call(undefined) 返回 “[object Undefined]”
  • “[object Undefined]”.match(/\b\s\w+\b/g)[0] // 匹配獲取到 ’ Object’
  • .trim() // 去掉空格得到 ‘Object’
  • .toLowerCase() // 大小寫轉換得到 ‘object’ 或
  • .toUpperCase() // 大小寫轉換得到 ‘OBJECT’
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章