Skip to content

Latest commit

 

History

History
52 lines (42 loc) · 1.34 KB

typeof.md

File metadata and controls

52 lines (42 loc) · 1.34 KB

自己手写 typeof

原生 typeof 对于简单数据类型是可以准确判断的, 但是对于引用类型除了 function 其他均会返回 object

  • 识别所有值类型
  • 识别函数
  • 判断是否是引用类型
  typeof undefined // "undefined"
  typeof "abc" // "string""
  typeof 100 // "number""
  typeof true // "boolean""
  typeof Symbol('a') // "symbol"

  typeof funcion() {} // "function"

  typeof null // "object"
  typeof [] // "object"
  typeof {} // "object"

所以我们可以自己实现一个 typeof

function myTypeof(item) {
  if (typeof item !== 'object') return typeof item
  return Object.toString.call(item).slice(8, -1).toLowerCase()
} // 这样基本可以精确判断数据类型

Object.prototype.toString

通过toString检测所有数据类型

let toString = e => Object.prototype.toString.call(e)

toString('') // [object String]
toString([]) // [object Array]
toString({}) // [object Object]
toString(/./) // [object RegExp]
toString(12) // [object Number]
toString(Symbol('1')) // [object Symbol]
toString(new Set()) // [object Set]
toString(new Map()) // [object Map]
toString(arguments) // 函数内部[object Arguments]
toString(Math) // [object Math]
toString(new Date()) // [object Date]
toString(function () {}) // [object Function]
toString(() => {}) // [object Function]

感叹一句, nb !