Object.getOwnPropertyNames()
Object.getOwnPropertyNames()
静态方法会返回一个数组,该数组包含给定对象中存在的所有属性(包括不可枚举属性,但不包括使用 Symbol 的属性)。
试一试
const object = {
a: 1,
b: 2,
c: 3,
};
console.log(Object.getOwnPropertyNames(object));
// Expected output: Array ["a", "b", "c"]
语法
js
Object.getOwnPropertyNames(obj)
参数
obj
-
要返回其可枚举和不可枚举属性的对象。
返回值
与给定对象中直接找到的属性相对应的字符串数组。
描述
Object.getOwnPropertyNames()
返回一个数组,其元素是字符串,对应于在给定对象 obj
中直接找到的可枚举和不可枚举属性。可枚举属性在数组中的顺序与使用 for...in
循环(或 Object.keys()
)遍历对象属性时暴露的顺序一致。对象(可枚举和不可枚举)的非负整数键将按升序添加到数组中,然后是字符串键,按插入顺序排列。
在 ES5 中,如果此方法的参数不是对象(原始值),则会引发 TypeError
。在 ES2015 中,非对象参数将被强制转换为对象。
js
Object.getOwnPropertyNames("foo");
// TypeError: "foo" is not an object (ES5 code)
Object.getOwnPropertyNames("foo");
// ["0", "1", "2", "length"] (ES2015 code)
示例
使用 Object.getOwnPropertyNames()
js
const arr = ["a", "b", "c"];
console.log(Object.getOwnPropertyNames(arr).sort());
// ["0", "1", "2", "length"]
// Array-like object
const obj = { 0: "a", 1: "b", 2: "c" };
console.log(Object.getOwnPropertyNames(obj).sort());
// ["0", "1", "2"]
Object.getOwnPropertyNames(obj).forEach((val, idx, array) => {
console.log(`${val} -> ${obj[val]}`);
});
// 0 -> a
// 1 -> b
// 2 -> c
// non-enumerable property
const myObj = Object.create(
{},
{
getFoo: {
value() {
return this.foo;
},
enumerable: false,
},
},
);
myObj.foo = 1;
console.log(Object.getOwnPropertyNames(myObj).sort()); // ["foo", "getFoo"]
如果您只想要可枚举属性,请参阅 Object.keys()
或使用 for...in
循环(请注意,这还会返回对象原型链上找到的可枚举属性,除非后者使用 Object.hasOwn()
进行过滤)。
原型链上的项不会被列出
js
function ParentClass() {}
ParentClass.prototype.inheritedMethod = function () {};
function ChildClass() {
this.prop = 5;
this.method = function () {};
}
ChildClass.prototype = new ParentClass();
ChildClass.prototype.prototypeMethod = function () {};
console.log(Object.getOwnPropertyNames(new ChildClass()));
// ["prop", "method"]
仅获取不可枚举属性
这使用了 Array.prototype.filter()
函数,从所有键的列表中(通过 Object.getOwnPropertyNames()
获取)删除可枚举键(通过 Object.keys()
获取),从而只输出不可枚举键。
js
const target = myObject;
const enumAndNonEnum = Object.getOwnPropertyNames(target);
const enumOnly = new Set(Object.keys(target));
const nonEnumOnly = enumAndNonEnum.filter((key) => !enumOnly.has(key));
console.log(nonEnumOnly);
规范
规范 |
---|
ECMAScript® 2026 语言规范 # sec-object.getownpropertynames |
浏览器兼容性
加载中…