How to list the properties of a JavaScript object?

后端 未结 17 2962
刺人心
刺人心 2020-11-22 00:34

Say I create an object thus:

var myObject =
        {\"ircEvent\": \"PRIVMSG\", \"method\": \"newURI\", \"regex\": \"^http://.*\"};

What is

17条回答
  •  天命终不由人
    2020-11-22 01:29

    The solution work on my cases and cross-browser:

    var getKeys = function(obj) {
        var type = typeof  obj;
        var isObjectType = type === 'function' || type === 'object' || !!obj;
    
        // 1
        if(isObjectType) {
            return Object.keys(obj);
        }
    
        // 2
        var keys = [];
        for(var i in obj) {
            if(obj.hasOwnProperty(i)) {
                keys.push(i)
            }
        }
        if(keys.length) {
            return keys;
        }
    
        // 3 - bug for ie9 <
        var hasEnumbug = !{toString: null}.propertyIsEnumerable('toString');
        if(hasEnumbug) {
            var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',
                'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];
    
            var nonEnumIdx = nonEnumerableProps.length;
    
            while (nonEnumIdx--) {
                var prop = nonEnumerableProps[nonEnumIdx];
                if (Object.prototype.hasOwnProperty.call(obj, prop)) {
                    keys.push(prop);
                }
            }
    
        }
    
        return keys;
    };
    

提交回复
热议问题