How to list the properties of a JavaScript object?

后端 未结 17 2906
刺人心
刺人心 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:36

    Mozilla has full implementation details on how to do it in a browser where it isn't supported, if that helps:

    if (!Object.keys) {
      Object.keys = (function () {
        var hasOwnProperty = Object.prototype.hasOwnProperty,
            hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
            dontEnums = [
              'toString',
              'toLocaleString',
              'valueOf',
              'hasOwnProperty',
              'isPrototypeOf',
              'propertyIsEnumerable',
              'constructor'
            ],
            dontEnumsLength = dontEnums.length;
    
        return function (obj) {
          if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) throw new TypeError('Object.keys called on non-object');
    
          var result = [];
    
          for (var prop in obj) {
            if (hasOwnProperty.call(obj, prop)) result.push(prop);
          }
    
          if (hasDontEnumBug) {
            for (var i=0; i < dontEnumsLength; i++) {
              if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
            }
          }
          return result;
        };
      })();
    }
    

    You could include it however you'd like, but possibly in some kind of extensions.js file at the top of your script stack.

提交回复
热议问题