全新的typeof

11/21/2021 #javascript

Object.prototype.toString

js源生的typeof关键字并不好用,比如最典型的就是不能识别Array以及把null也识别成object。并且除了几个基本类型以外的object统一识别为object。

由于js的所有类型都是Object。那么我们利用Object原型链上toString这个函数便可以判断任何类型。Object.prototype.toString的具体效果是返回一个类似[object 构造函数名]的字符串。

const type = Object.prototype.toString.call(new Array())
console.log(type) //[object Array]

实际上object和中括号都可以去掉

type = type.slice(8, -1) // 'Array'

取lowercase

type = type.toLowerCase() // 'array'

包装起来

function newTypeof(any){
  const typeString = Object.prototype.toString.call(any) 
  const type = typeString.slice(8, -1)
  return type.toLowerCase()
}

测试一下

newtypeof([]) // 'array'
newtypeof({}) // 'object'
newtypeof(123) // 'number'
newtypeof(new Set()) // 'set'
newtypeof(document.createElement("div")) // 'htmldivelement'
newtypeof(undefined) // undefined
newtypeof(null) //null

NaN

但是还有一个特殊情况, NaN的类型是'number',但是他又不能像正常数字一样进行运算,所以newtypeof里需要把NaN像undefined一样对待. 利用NaN的一个独特特性: 它不等于自身,我们可以很快找出变量是否是NaN

const na = NaN
console.log(na === na) // false
console.log(na === NaN) // false
console.log(NaN === NaN) // false

最后

修改后的newtypeof

function newTypeof(any){
  if (any !== any) { return NaN }
  const typeString = Object.prototype.toString.call(any) 
  const type = typeString.slice(8, -1)
  return type.toLowerCase()
}