正如 Sam Dutton 所回答的,ECMAScript 第 5 版中引入了一种用于此目的的新方法。 Object.keys() 会做你想做的事,并在Firefox 4、Chrome 6、Safari 5 和IE 9 中得到支持。
您也可以在不支持该方法的浏览器中轻松实现该方法。但是,那里的一些实现与 Internet Explorer 不完全兼容。这是一个更兼容的解决方案:
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 (o) {
if (typeof o != "object" && typeof o != "function" || o === null)
throw new TypeError("Object.keys called on a non-object");
var result = [];
for (var name in o) {
if (hasOwnProperty.call(o, name))
result.push(name);
}
if (hasDontEnumBug) {
for (var i = 0; i < DontEnumsLength; i++) {
if (hasOwnProperty.call(o, DontEnums[i]))
result.push(DontEnums[i]);
}
}
return result;
};
})();
请注意,当前接受的答案不包括对 hasOwnProperty() 的检查,并且将返回通过原型链继承的属性。它也没有解释 Internet Explorer 中著名的 DontEnum 错误,即原型链上的不可枚举属性导致本地声明的同名属性继承其 DontEnum 属性。
实施 Object.keys() 将为您提供更强大的解决方案。
编辑:在最近与 Prototype 的知名贡献者 kangax 讨论之后,我根据找到的 Object.forIn() 函数的代码实现了 DontEnum 错误的解决方法here .