javascript check if dictionary

后端 未结 7 2486
旧巷少年郎
旧巷少年郎 2021-02-07 11:37

I have a simple program like:

var a = {\'a\': 1, \'b\': 2}
console.log(a)
console.log(a instanceof Array)
console.log(a.constructor instanceof Array)
         


        
7条回答
  •  南旧
    南旧 (楼主)
    2021-02-07 12:06

    The structure {'a': 1, 'b': 2} is a Javascript object. It can be used sort of like a dictionary, but Javascript does not have an actual dictionary type.

    console.log(typeof a);            // "object"
    console.log(Array.isArray(a));    // false, because it's not an array
    

    If you want to know if something is an array, then use:

    Array.isArray(a)
    

    If you want to know if something is an object, then use:

    typeof a === "object"
    

    But, you will have to be careful because an Array is an object too.


    If you want to know if something is a plain object, you can look at what jQuery does to detect a plain object:

    isPlainObject: function( obj ) {
        // Not plain objects:
        // - Any object or value whose internal [[Class]] property is not "[object Object]"
        // - DOM nodes
        // - window
        if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
            return false;
        }
    
        // Support: Firefox <20
        // The try/catch suppresses exceptions thrown when attempting to access
        // the "constructor" property of certain host objects, ie. |window.location|
        // https://bugzilla.mozilla.org/show_bug.cgi?id=814622
        try {
            if ( obj.constructor &&
                    !hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) {
                return false;
            }
        } catch ( e ) {
            return false;
        }
    
        // If the function hasn't returned already, we're confident that
        // |obj| is a plain object, created by {} or constructed with new Object
        return true;
    },
    

提交回复
热议问题