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

后端 未结 9 1043
借酒劲吻你
借酒劲吻你 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 05:42

    the Object.prototype.toString is a good way, but its performance is the worst.

    http://jsperf.com/check-js-type

    check js type performance

    Use typeof to solve some basic problem(String, Number, Boolean...) and use Object.prototype.toString to solve something complex(like Array, Date, RegExp).

    and this is my solution:

    var type = (function(global) {
        var cache = {};
        return function(obj) {
            var key;
            return obj === null ? 'null' // null
                : obj === global ? 'global' // window in browser or global in nodejs
                : (key = typeof obj) !== 'object' ? key // basic: string, boolean, number, undefined, function
                : obj.nodeType ? 'object' // DOM element
                : cache[key = ({}).toString.call(obj)] // cached. date, regexp, error, object, array, math
                || (cache[key] = key.slice(8, -1).toLowerCase()); // get XXXX from [object XXXX], and cache it
        };
    }(this));
    

    use as:

    type(function(){}); // -> "function"
    type([1, 2, 3]); // -> "array"
    type(new Date()); // -> "date"
    type({}); // -> "object"
    

提交回复
热议问题