what is the best way to check variable type in javascript

后端 未结 6 802
天涯浪人
天涯浪人 2020-12-15 22:41


        
6条回答
  •  孤城傲影
    2020-12-15 23:04

    The best way is using typeof

    typeof "blahha" 
    

    I made a function with help of jQuery library code, jQuery library type method github link .

    var getType = (function() {
    
        var objToString = ({}).toString ,
            typeMap     = {},
            types = [ 
              "Boolean", 
              "Number", 
              "String",                
              "Function", 
              "Array", 
              "Date",
              "RegExp", 
              "Object", 
              "Error"
            ];
    
        for ( var i = 0; i < types.length ; i++ ){
            typeMap[ "[object " + types[i] + "]" ] = types[i].toLowerCase();
        };    
    
        return function( obj ){
            if ( obj == null ) {
                return String( obj );
            }
            // Support: Safari <= 5.1 (functionish RegExp)
            return typeof obj === "object" || typeof obj === "function" ?
                typeMap[ objToString.call(obj) ] || "object" :
                typeof obj;
        }
    }());
    

    You can call it as getType("Hello")

提交回复
热议问题