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

后端 未结 9 1012
借酒劲吻你
借酒劲吻你 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.

提交回复
热议问题