The most accurate way to check JS object's type?

后端 未结 9 984
借酒劲吻你
借酒劲吻你 2020-12-04 05:33

The typeof operator doesn\'t really help us to find the real type of an object.

I\'ve already seen the following code :

Object.prototyp         


        
相关标签:
9条回答
  • 2020-12-04 06:02

    Old question I know. You don't need to convert it. See this function:

    function getType( oObj )
    {
        if( typeof oObj === "object" )
        {
              return ( oObj === null )?'Null':
              // Check if it is an alien object, for example created as {world:'hello'}
              ( typeof oObj.constructor !== "function" )?'Object':
              // else return object name (string)
              oObj.constructor.name;              
        }   
    
        // Test simple types (not constructed types)
        return ( typeof oObj === "boolean")?'Boolean':
               ( typeof oObj === "number")?'Number':
               ( typeof oObj === "string")?'String':
               ( typeof oObj === "function")?'Function':false;
    
    }; 
    

    Examples:

    function MyObject() {}; // Just for example
    
    console.log( getType( new String( "hello ") )); // String
    console.log( getType( new Function() );         // Function
    console.log( getType( {} ));                    // Object
    console.log( getType( [] ));                    // Array
    console.log( getType( new MyObject() ));        // MyObject
    
    var bTest = false,
        uAny,  // Is undefined
        fTest  function() {};
    
     // Non constructed standard types
    console.log( getType( bTest ));                 // Boolean
    console.log( getType( 1.00 ));                  // Number
    console.log( getType( 2000 ));                  // Number
    console.log( getType( 'hello' ));               // String
    console.log( getType( "hello" ));               // String
    console.log( getType( fTest ));                 // Function
    console.log( getType( uAny ));                  // false, cannot produce
                                                    // a string
    

    Low cost and simple.

    0 讨论(0)
  • 2020-12-04 06:08

    The best way to find out the REAL type of an object (including BOTH the native Object or DataType name (such as String, Date, Number, ..etc) AND the REAL type of an object (even custom ones); is by grabbing the name property of the object prototype's constructor:

    Native Type Ex1:

    var string1 = "Test";
    console.log(string1.__proto__.constructor.name);
    

    displays:

    String
    

    Ex2:

    var array1 = [];
    console.log(array1.__proto__.constructor.name);
    

    displays:

    Array
    

    Custom Classes:

    function CustomClass(){
      console.log("Custom Class Object Created!");
    }
    var custom1 = new CustomClass();
    
    console.log(custom1.__proto__.constructor.name);

    displays:

    CustomClass
    
    0 讨论(0)
  • 2020-12-04 06:08

    I put together a little type check utility inspired by the above correct answers:

    thetypeof = function(name) {
            let obj = {};
            obj.object = 'object Object'
            obj.array = 'object Array'
            obj.string = 'object String'
            obj.boolean = 'object Boolean'
            obj.number = 'object Number'
            obj.type = Object.prototype.toString.call(name).slice(1, -1)
            obj.name = Object.prototype.toString.call(name).slice(8, -1)
            obj.is = (ofType) => {
                ofType = ofType.toLowerCase();
                return (obj.type === obj[ofType])? true: false
            }
            obj.isnt = (ofType) => {
                ofType = ofType.toLowerCase();
                return (obj.type !== obj[ofType])? true: false
            }
            obj.error = (ofType) => {
                throw new TypeError(`The type of ${name} is ${obj.name}: `
                +`it should be of type ${ofType}`)
            }
            return obj;
        };
    

    example:

    if (thetypeof(prop).isnt('String')) thetypeof(prop).error('String')
    if (thetypeof(prop).is('Number')) // do something
    
    0 讨论(0)
提交回复
热议问题