JavaScript 获得变量的类型

2019-02-13  本文已影响0人  Mr老朝
168d78d3d887d7bb.png

根据上图

function toRawType (value) {
  return Object.prototype.toString.call(value).slice(8, -1)
}

toRawType() //Undefined
toRawType(null) // Null
toRawType([]) //Array
toRawType('') //String
(function() {return toRawType(arguments)})() //Arguments
toRawType(_=>_) //Function
toRawType(new Error()) //Error
toRawType(false) //Boolean
toRawType(0) //Number
toRawType(new Date()) //Date
toRawType(/a/) // RegExp
toRawType({}) //Object
toRawType(new Set()) //Set
toRawType(new WeakSet()) //WeakSet
toRawType(new Map()) //Map
toRawType(new WeakMap()) //WeakMap
toRawType(Symbol()) //Symbol
toRawType(new Promise(_=>_)) //Promise
toRawType(function* helloWorldGenerator() {}) //GeneratorFunction
toRawType(async function () {}) //AsyncFunction
toRawType(new ArrayBuffer()) //ArrayBuffer
toRawType(new Int32Array()) //Int32Array
toRawType(new Uint8Array()) //Uint8Array
toRawType(new Int16Array()) //Int16Array

js新特性支持还算良好,注意下面两种情况

toRawType(class Point {}) //Function
toRawType(new Proxy({},{})) //Object
上一篇 下一篇

猜你喜欢

热点阅读