Check if a value is an object in JavaScript

后端 未结 30 3369
臣服心动
臣服心动 2020-11-22 05:06

How do you check if a value is an object in JavaScript?

30条回答
  •  名媛妹妹
    2020-11-22 05:53

    Since there seems a lot of confusion about how to handle this problem correctly, I'll leave my 2 cents (this answer is spec compliant and produces correct results under all circumstances):

    Testing for primitives: undefined null boolean string number

    function isPrimitive(o){return typeof o!=='object'||null}
    

    An object is not a primitive:

    function isObject(o){return !isPrimitive(o)}
    

    Or alternatively:

    function isObject(o){return o instanceof Object}
    function isPrimitive(o){return !isObject(o)}
    

    Testing for any Array:

    const isArray=(function(){
        const arrayTypes=Object.create(null);
        arrayTypes['Array']=true;
        arrayTypes['Int8Array']=true;
        arrayTypes['Uint8Array']=true;
        arrayTypes['Uint8ClampedArray']=true;
        arrayTypes['Int16Array']=true;
        arrayTypes['Uint16Array']=true;
        arrayTypes['Int32Array']=true;
        arrayTypes['Uint32Array']=true;
        arrayTypes['BigInt64Array']=true;
        arrayTypes['BigUint64Array']=true;
        arrayTypes['Float32Array']=true;
        arrayTypes['Float64Array']=true;
        return function(o){
            if (!o) return false;
            return !isPrimitive(o)&&!!arrayTypes[o.constructor.name];
        }
    }());
    

    Testing for object excluding: Date RegExp Boolean Number String Function any Array

    const isObjectStrict=(function(){
        const nativeTypes=Object.create(null);
        nativeTypes['Date']=true;
        nativeTypes['RegExp']=true;
        nativeTypes['Boolean']=true;
        nativeTypes['Number']=true;
        nativeTypes['String']=true;
        nativeTypes['Function']=true;
        return function(o){
            if (!o) return false;
            return !isPrimitive(o)&&!isArray(o)&&!nativeTypes[o.constructor.name];
        }
    }());
    

提交回复
热议问题