假设我这样创建一个对象:

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

检索属性名列表的最佳方法是什么?例如,我想以一些变量“键”结束,这样:

keys == ["ircEvent", "method", "regex"]

当前回答

因为我几乎在每个项目中都使用了underscore.js,所以我会使用keys函数:

var obj = {name: 'gach', hello: 'world'};
console.log(_.keys(obj));

它的输出将是:

['name', 'hello']

其他回答

Mozilla有完整的实现细节,关于如何在不支持它的浏览器中实现它,如果这有帮助的话:

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;
    };
  })();
}

你可以把它包括在你喜欢的任何地方,但可能是在脚本堆栈顶部的某种extensions.js文件中。

可以用jQuery这样做:

var objectKeys = $.map(object, function(value, key) {
  return key;
});

IE不支持(i in obj)原生属性。这是我能找到的所有道具的清单。

似乎stackoverflow做了一些愚蠢的过滤。

该列表可在这个谷歌组帖子的底部:- https://groups.google.com/group/hackvertor/browse_thread/thread/a9ba81ca642a63e0

我是转储功能的超级粉丝。

ajax»JavaScript变量转储在Coldfusion

下载转储功能

使用Reflect.ownKeys ()

var obj = {a: 1, b: 2, c: 3};
Reflect.ownKeys(obj) // ["a", "b", "c"]

对象。键和对象。getOwnPropertyNames不能获得不可枚举的属性。它甚至适用于不可枚举的属性。

var obj = {a: 1, b: 2, c: 3};
obj[Symbol()] = 4;
Reflect.ownKeys(obj) // ["a", "b", "c", Symbol()]