Js实现allkeys
实现 allKeys 方法
在 JavaScript 中,allKeys 方法通常用于获取对象的所有可枚举属性(包括原型链上的属性)。以下是几种实现方式:
使用 for...in 循环
通过 for...in 循环遍历对象及其原型链上的所有可枚举属性:
function allKeys(obj) {
const keys = [];
for (const key in obj) {
keys.push(key);
}
return keys;
}
const obj = { a: 1, b: 2 };
const childObj = Object.create(obj);
childObj.c = 3;
console.log(allKeys(childObj)); // ["c", "a", "b"]
结合 Object.getOwnPropertyNames 和递归
如果需要包含不可枚举属性,可以结合 Object.getOwnPropertyNames 和递归遍历原型链:
function allKeys(obj) {
const keys = [];
let current = obj;
while (current !== null && current !== Object.prototype) {
Object.getOwnPropertyNames(current).forEach(key => {
if (!keys.includes(key)) {
keys.push(key);
}
});
current = Object.getPrototypeOf(current);
}
return keys;
}
const obj = { a: 1, b: 2 };
Object.defineProperty(obj, 'hidden', { enumerable: false, value: 3 });
console.log(allKeys(obj)); // ["a", "b", "hidden"]
使用 Reflect.ownKeys
如果需要包含 Symbol 类型的属性,可以使用 Reflect.ownKeys:
function allKeys(obj) {
const keys = new Set();
let current = obj;
while (current !== null && current !== Object.prototype) {
Reflect.ownKeys(current).forEach(key => keys.add(key));
current = Object.getPrototypeOf(current);
}
return Array.from(keys);
}
const obj = { a: 1, [Symbol('id')]: 2 };
console.log(allKeys(obj)); // ["a", Symbol(id)]
注意事项
for...in会跳过 Symbol 类型的属性。Object.getOwnPropertyNames会包含不可枚举属性,但不会包含 Symbol 属性。Reflect.ownKeys是最全面的方法,包含所有自有属性(包括 Symbol 和不可枚举属性)。- 递归遍历原型链时需注意终止条件(
Object.prototype或null)。







