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 |
瀏覽器相容性
載入中…