Get the name of an object's type

前端 未结 20 2297
忘掉有多难
忘掉有多难 2020-11-21 22:37

Is there a JavaScript equivalent of Java\'s class.getName()?

20条回答
  •  遥遥无期
    2020-11-21 22:53

    Using Object.prototype.toString

    It turns out, as this post details, you can use Object.prototype.toString - the low level and generic implementation of toString - to get the type for all built-in types

    Object.prototype.toString.call('abc') // [object String]
    Object.prototype.toString.call(/abc/) // [object RegExp]
    Object.prototype.toString.call([1,2,3]) // [object Array]
    

    One could write a short helper function such as

    function type(obj){
        return Object.prototype.toString.call(obj]).match(/\s\w+/)[0].trim()
    }
    
    return [object String] as String
    return [object Number] as Number
    return [object Object] as Object
    return [object Undefined] as Undefined
    return [object Function] as Function
    

提交回复
热议问题