Object.getOwnPropertyNames(obj) 静态方法返回一个数组,其包含给定对象中所有自有属性(包括不可枚举属性,但不包括使用 symbol 值作为名称的属性)。
非对象参数会被强制转换为对象
Object.getOwnPropertyNames("foo");
// ["0", "1", "2", "length"] (ES2015 code)
基本使用
const arr = ["a", "b", "c"];
console.log(Object.getOwnPropertyNames(arr).sort());
// ["0", "1", "2", "length"]
// 类数组对象
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
// 不可枚举属性
const myObj = Object.create(
{},
{
getFoo: {
value() {
return this.foo;
},
enumerable: false,
},
},
);
myObj.foo = 1;
console.log(Object.getOwnPropertyNames(myObj).sort()); // ["foo", "getFoo"]
原型链上的属性不会被列出
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"]
只获取不可枚举的属性
function enumerableFilter(target) {
const enumAndNonenum = Object.getOwnPropertyNames(target);
const enumOnly = new Set(Object.keys(target));
const nonenumOnly = enumAndNonenum.filter((key) => !enumOnly.has(key));
return nonenumOnly;
}