Object.keys、Object.values 与 Object.entries:枚举顺序和 getter 副作用实测
Object.keys、Object.values 和 Object.entries 很适合把配置对象转换成列表,但它们枚举的并不是“对象里所有能访问到的东西”。三者都筛选对象自身的、可枚举的字符串键;区别在于返回键、值,还是 [键, 值] 二元数组。真正容易踩坑的地方,是数字外观的键、数组空槽,以及读取 getter 时发生的修改。
本文用 36 组手工推导预期的确定性用例,以及 8 个故意写错的包装函数,解释这些边界。测试使用 Node.js v24.19.0,没有安装依赖,不使用代理对象,不做性能排名。文末提供完整自包含测试脚本。
配图为独立模型生成的概念示意图,不是真实界面截图。它只表达筛选与输出形态,不表示所有对象都具有固定的数据快照。
先确定你要列出的是什么
对普通对象而言,Object.keys 返回字符串键数组,Object.values 返回相应的值数组,Object.entries 返回由二元数组组成的数组。继承属性不在范围内;不可枚举属性和 Symbol 键也不会进入结果,即使你能用方括号正常访问它们。MDN 的三份参考文档分别说明了这三个接口:Object.keys、Object.values、Object.entries。
下面只用 Reflect.ownKeys 作一个边界对照:它能列出对象自身的字符串键与 Symbol 键,而且不按可枚举性筛掉属性。因此,不能直接把它当成 Object.keys 的替代品。
const assert = require('node:assert/strict');
const o = { visible: 1 };
Object.defineProperty(o, 'hidden', { value: 2 });
o[Symbol('s')] = 3;
assert.deepEqual(Object.keys(o), ['visible']);
assert.deepEqual(Reflect.ownKeys(o).map(String),
['visible', 'hidden', 'Symbol(s)']);
console.log('filter example passed');这里的 String 转换仅为了显示 Symbol(s),不是说 Symbol 键在对象内部变成了字符串。测试中的隐藏属性由 Object.defineProperty 创建,省略 enumerable 后默认不可枚举。空原型对象同样可以使用这些静态方法,不需要对象自己带有任何辅助方法。
排序规则中的关键字是数组索引
普通对象先列出数组索引键,按数值升序排列;再列出其他字符串键,按属性创建的先后排列。对象自身的 Symbol 键在底层键列表中有自己的顺序,但这三个接口会将它们排除。依据是当前在线 ECMAScript 规范的 OrdinaryOwnPropertyKeys,这里不把规范网页标题中的年份当成年度标准已经发布的消息。
数组索引不能简单理解成“看起来像整数”。符合条件的字符串对应 0 到 4294967294;"4294967295" 已经越过边界。"02"、"1.0" 和 "-0" 也不会进入这个排序分组。规范还定义了范围更大的 integer index,不能把它与这里的 array index 混用。属性键与索引定义解释了两者的边界。
const assert = require('node:assert/strict');
const o = { '4294967295': 5, z: 0, '4294967294': 4, 1: 1 };
assert.deepEqual(Object.keys(o),
['1', '4294967294', '4294967295', 'z']);
assert.deepEqual(Object.keys({ '02': 2, '-0': 0, '1.0': 1, 1: 1, 0: 0 }),
['0', '1', '02', '-0', '1.0']);
console.log('ordering example passed');因此,既不能概括为“严格按插入顺序”,也不能概括为“全部按字符串排序”。重写已有普通字符串属性的值不会改变它的创建位置;删除后重新创建,则会排到这一组字符串键的后面。数组索引键即使删除再加回来,仍按数值排序。完整脚本中的 08 至 13 组覆盖了这些差别。
数组空槽与值为 undefined 的元素不同
这些接口处理数组时仍在枚举属性,而不是从 0 遍历到 length - 1。空槽没有对应的自身属性,所以被跳过;真正存在但值为 undefined 的元素则会保留。数组的 length 通常不可枚举,不会进入结果;自己加上的可枚举字符串属性,例如 note,则会进入结果。
const assert = require('node:assert/strict');
const a = [, undefined];
assert.deepEqual(Object.entries(a), [['1', undefined]]);
assert.equal(Object.entries(a).length, 1);
assert.equal(a.length, 2);
console.log('sparse example passed');结果中的索引仍是字符串 "1",不是数字 1。稀疏数组也不会因为枚举而补齐空槽。完整测试还给一个数组设置了独立的局部原型,在原型上放入索引 0;Object.entries 依然只返回自身的索引 1。测试没有修改全局 Array.prototype。
原始值会装箱 但 null 和 undefined 不行
这三个方法会先执行对象转换。字符串 "hi" 的 entries 是 [["0", "h"], ["1", "i"]]。字符串索引对应 UTF-16 码元,所以一个需要代理对表示的字符会产生两个索引;不要把这个结果当成按用户看到的字符切分。
本文测试的数字、布尔值、BigInt 和 Symbol 原始值装箱后没有可枚举的自身属性,三种枚举结果都是空数组。null 和 undefined 则在转换阶段抛出 TypeError。这些输入规则见 MDN 的原始值示例及 Object.entries 规范入口。
如果业务希望把 null 当成空对象,可以明确制定这个输入契约;但 Object.entries(value || {}) 已经改变了原生方法的行为,不应再称为等价实现。完整测试的第 19 至 23 组和 W07 反例会检查这些情况。
键列表先取得 值却是逐个读取的
理解副作用时,把几个阶段分开比记“快照”更可靠。当前规范的 EnumerableOwnProperties 先取得对象自身的键列表,然后按顺序处理每个字符串键:当时再查看它是否仍是自身属性、是否仍可枚举;若需要值,再执行属性读取。
Object.keys 的这个过程不读取普通对象属性的值,因此不会调用属性 getter。Object.values 和 Object.entries 则会读取符合条件的属性值,可能执行 getter。这个结论限定在本文的普通对象与内置对象样例范围内,不能扩展成对任意对象都绝无副作用的承诺。
const assert = require('node:assert/strict');
function make() {
return {
get a() {
Object.defineProperty(this, 'b', { enumerable: false });
return 1;
},
b: 2
};
}
assert.deepEqual(Object.entries(make()), [['a', 1]]);
const o = make();
assert.deepEqual(Object.keys(o).map(k => [k, o[k]]),
[['a', 1], ['b', 2]]);
console.log('getter example passed');两边使用了新建对象,避免前一次 getter 修改干扰后一次实验。原生 entries 读取 a 后,b 已经变为不可枚举,所以跳过它;keys 加 map 的写法先把可枚举键数组拿完,随后读取 a 时才发生修改,map 仍会继续处理数组中的 b。它们对静态普通数据常常给出相同结果,但不是所有输入上的等价算法。
同一个阶段模型还解释了完整测试中的几个结果:
先前的 getter 删除后续属性,或把它改为不可枚举,后续属性会被跳过。
getter 新增一个最初不存在的键,这个键不在最初的键列表中,本次不会访问它。
一个最初存在但不可枚举的键,本来就在自身键列表里。如果轮到它之前被改成可枚举,本次可以进入结果。
getter 修改后续属性的值,后续读取能拿到修改后的值。删除再重建后续属性,也不会重新排序本次已经取得的键列表。
删除自身属性后,即使原型上有同名属性,这次枚举也不会改为返回继承属性。
这些都是同步的小型合成实验,不依赖定时器或线程调度。结论是“键列表先取得,描述符与值稍后逐项检查”,而不是“调用开始时冻结了所有属性和值”。
异常会中断返回 结果也不是深拷贝
如果合格属性的 getter 抛出异常,values 或 entries 会把异常向外传播,后续 getter 不再读取,也不会向调用者返回一个半成品数组。已经发生的 getter 副作用不会自动回滚。第 34 组用访问记录验证中断位置,而不是只判断有没有异常。
返回数组是新数组,entries 内部的每个二元数组也是新建的。但值如果是对象,保存的仍是原对象引用。把一个 entry 的第二项从 1 换成 7,不会改写源对象那个数字属性;沿着 entry 保存的对象引用修改嵌套字段,则会影响同一个嵌套对象。第 35 组同时检查这两种情况。只有 setter、没有 getter 的可枚举访问器,读取结果是 undefined,第 36 组专门保留了这个边界。
完整可复制测试
下面第一个代码块完整保存为 public-tests.cjs,直接运行 node public-tests.cjs 即可。它内嵌了独立预期数据、冻结记录、36 组用例和 8 个错误包装反例,不需要下载其他测试数据文件,也不依赖本文工作目录。每个反例既核对正确结果与错误结果,也要求两者确实不同。
其中 {$undefined: true} 只是本测试的 JSON 证据标记,用来避免 JSON.stringify 把数组中的 undefined 写成 null;它不是被测 API 的返回值。所有合成输入都避开了与这个标记冲突的普通业务对象。
const assert = require('node:assert/strict');
const fs = require('node:fs');
const crypto = require('node:crypto');
// Independently hand-derived and frozen before the first behavioral run.
const expectedBytes = Buffer.from(String.raw`{
"cases": {
"01_basic_keys": ["b", "a"],
"02_basic_values": [2, 1],
"03_basic_entries": [["b", 2], ["a", 1]],
"04_inherited_excluded": [["own", 1]],
"05_non_enumerable_excluded": [["visible", 1]],
"06_symbol_excluded": {"keys": ["visible"], "all": ["visible", "hidden", "Symbol(s)"]},
"07_null_prototype": [["toString", 3]],
"08_index_order": ["2", "7", "10", "z", "a"],
"09_numeric_looking_strings": ["0", "1", "02", "-0", "1.0"],
"10_array_index_boundary": ["1", "4294967294", "4294967295", "z"],
"11_recreate_string": ["b", "a"],
"12_redefine_string": ["a", "b"],
"13_recreate_index": ["2", "10"],
"14_dense_array": [["0", "A"], ["1", "B"]],
"15_sparse_array": [["1", "B"]],
"16_hole_vs_undefined": [["1", {"$undefined": true}]],
"17_array_extra_property": [["2", "C"], ["note", "N"]],
"18_inherited_array_index": [["1", "B"]],
"19_string_boxing": [["0", "h"], ["1", "i"]],
"20_string_utf16": [55357, 56832],
"21_other_primitives": [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]],
"22_null_throws": ["TypeError", "TypeError", "TypeError"],
"23_undefined_throws": ["TypeError", "TypeError", "TypeError"],
"24_keys_skips_getter": {"keys": ["x"], "reads": 0},
"25_values_reads_getter": {"values": [7], "reads": 1},
"26_entries_getter_receiver": {"entries": [["x", 7]], "sameReceiver": true},
"27_delete_later": {"entries": [["a", 1]], "keysAfter": ["a"]},
"28_hide_later": [["a", 1]],
"29_add_new_key": {"entries": [["a", 1], ["b", 2]], "keysAfter": ["a", "b", "c"]},
"30_expose_existing_key": [["a", 1], ["b", 2]],
"31_change_later_value": [["a", 1], ["b", 9]],
"32_recreate_later_key": {"entries": [["a", 1], ["b", 9], ["c", 3]], "keysAfter": ["a", "c", "b"]},
"33_delete_reveals_prototype": {"entries": [["a", 1]], "lookupAfter": 99},
"34_throw_stops_access": {"entries": {"error": "RangeError", "trace": ["a"]}, "values": {"error": "RangeError", "trace": ["a"]}},
"35_shallow_result": [1, 9, true],
"36_setter_only": [["x", {"$undefined": true}]]
},
"probes": {
"W01_for_in": {"correct": [["own", 1]], "wrong": [["own", 1], ["inherited", 9]]},
"W02_names_without_filter": {"correct": [["visible", 1]], "wrong": [["visible", 1], ["hidden", 2]]},
"W03_reflect_without_filter": {"correct": ["visible"], "wrong": ["visible", "Symbol(s)"]},
"W04_lexical_sort": {"correct": ["2", "10"], "wrong": ["10", "2"]},
"W05_length_loop": {"correct": ["C"], "wrong": [{"$undefined": true}, {"$undefined": true}, "C"]},
"W06_keys_then_map": {"correct": [["a", 1]], "wrong": [["a", 1], ["b", 2]]},
"W07_null_fallback": {"correct": {"error": "TypeError"}, "wrong": []},
"W08_entries_for_keys": {"correct": ["a"], "wrong": {"error": "RangeError"}}
}
}
`, 'utf8');
const expected = JSON.parse(expectedBytes);
const freeze = {
"frozen_at_utc": "2026-10-21T22:43:34.638704+00:00",
"sha256": "415a6655f27167ec0d3b3e2190787c54909318dece5283d26f981db2804cccde",
"file": "expected.json",
"cases": 36,
"wrong_wrapper_probes": 8,
"basis": "Hand-derived from specification and small synthetic fixture plans. No behavioral execution has been performed; node --version only. Expected values were not copied from runtime output."
};
assert.equal(crypto.createHash('sha256').update(expectedBytes).digest('hex'), freeze.sha256);
// This fixture set never contains an ordinary {$undefined: true} value.
// The tag keeps actual undefined distinct from null in JSON evidence.
function normalize(value) {
return JSON.parse(JSON.stringify(value, (_key, item) =>
item === undefined ? { $undefined: true } : item));
}
function capture(fn) {
try { return fn(); } catch (error) { return { error: error.name }; }
}
function errorName(fn) {
try { fn(); return 'NO_ERROR'; } catch (error) { return error.name; }
}
function hiddenFixture() {
const o = { visible: 1 };
Object.defineProperty(o, 'hidden', { value: 2 });
return o;
}
function inheritedFixture() {
const o = Object.create({ inherited: 9 });
o.own = 1;
return o;
}
function hideLaterFixture() {
return {
get a() {
Object.defineProperty(this, 'b', { enumerable: false });
return 1;
},
b: 2
};
}
function throwFixture() {
return { get a() { throw new RangeError('fixture'); } };
}
const cases = {
'01_basic_keys': () => Object.keys({ b: 2, a: 1 }),
'02_basic_values': () => Object.values({ b: 2, a: 1 }),
'03_basic_entries': () => Object.entries({ b: 2, a: 1 }),
'04_inherited_excluded': () => Object.entries(inheritedFixture()),
'05_non_enumerable_excluded': () => Object.entries(hiddenFixture()),
'06_symbol_excluded': () => {
const o = hiddenFixture();
o[Symbol('s')] = 3;
return { keys: Object.keys(o), all: Reflect.ownKeys(o).map(String) };
},
'07_null_prototype': () => {
const o = Object.create(null);
o.toString = 3;
return Object.entries(o);
},
'08_index_order': () => Object.keys({ z: 0, 10: 10, 2: 2, a: 1, 7: 7 }),
'09_numeric_looking_strings': () =>
Object.keys({ '02': 2, '-0': 0, '1.0': 1, 1: 1, 0: 0 }),
'10_array_index_boundary': () =>
Object.keys({ '4294967295': 5, z: 0, '4294967294': 4, 1: 1 }),
'11_recreate_string': () => {
const o = { a: 1, b: 2 };
delete o.a; o.a = 3;
return Object.keys(o);
},
'12_redefine_string': () => {
const o = { a: 1, b: 2 };
Object.defineProperty(o, 'a', { value: 3 });
return Object.keys(o);
},
'13_recreate_index': () => {
const o = { 10: 10, 2: 2 };
delete o[2]; o[2] = 22;
return Object.keys(o);
},
'14_dense_array': () => Object.entries(['A', 'B']),
'15_sparse_array': () => {
const a = new Array(4); a[1] = 'B';
return Object.entries(a);
},
'16_hole_vs_undefined': () => Object.entries([, undefined]),
'17_array_extra_property': () => {
const a = new Array(4); a[2] = 'C'; a.note = 'N';
return Object.entries(a);
},
'18_inherited_array_index': () => {
const a = [, 'B'];
const p = Object.create(Array.prototype);
p[0] = 'inherited';
Object.setPrototypeOf(a, p); // Isolated prototype; no global mutation.
return Object.entries(a);
},
'19_string_boxing': () => Object.entries('hi'),
'20_string_utf16': () => Object.values('\u{1F600}').map(s => s.charCodeAt(0)),
'21_other_primitives': () => [3, false, 3n, Symbol('p')].map(v =>
[Object.keys(v).length, Object.values(v).length, Object.entries(v).length]),
'22_null_throws': () => [Object.keys, Object.values, Object.entries].map(fn =>
errorName(() => fn(null))),
'23_undefined_throws': () => [Object.keys, Object.values, Object.entries].map(fn =>
errorName(() => fn(undefined))),
'24_keys_skips_getter': () => {
let reads = 0;
const o = { get x() { reads++; return 7; } };
const keys = Object.keys(o);
return { keys, reads };
},
'25_values_reads_getter': () => {
let reads = 0;
const o = { get x() { reads++; return 7; } };
const values = Object.values(o);
return { values, reads };
},
'26_entries_getter_receiver': () => {
let sameReceiver = false;
const o = { get x() { sameReceiver = this === o; return 7; } };
const entries = Object.entries(o);
return { entries, sameReceiver };
},
'27_delete_later': () => {
const o = { get a() { delete this.b; return 1; }, b: 2 };
const entries = Object.entries(o);
return { entries, keysAfter: Object.keys(o) };
},
'28_hide_later': () => Object.entries(hideLaterFixture()),
'29_add_new_key': () => {
const o = { get a() { this.c = 3; return 1; }, b: 2 };
const entries = Object.entries(o);
return { entries, keysAfter: Object.keys(o) };
},
'30_expose_existing_key': () => {
const o = {
get a() {
Object.defineProperty(this, 'b', { enumerable: true });
return 1;
}
};
Object.defineProperty(o, 'b', { value: 2, configurable: true });
return Object.entries(o);
},
'31_change_later_value': () =>
Object.entries({ get a() { this.b = 9; return 1; }, b: 2 }),
'32_recreate_later_key': () => {
const o = {
get a() { delete this.b; this.b = 9; return 1; },
b: 2,
c: 3
};
const entries = Object.entries(o);
return { entries, keysAfter: Object.keys(o) };
},
'33_delete_reveals_prototype': () => {
const o = Object.create({ b: 99 });
Object.defineProperty(o, 'a', {
enumerable: true,
get() { delete this.b; return 1; }
});
o.b = 2;
const entries = Object.entries(o);
return { entries, lookupAfter: o.b };
},
'34_throw_stops_access': () => {
function run(method) {
const trace = [];
const o = {
get a() { trace.push('a'); throw new RangeError('fixture'); },
get b() { trace.push('b'); return 2; }
};
const outcome = capture(() => Object[method](o));
return { error: outcome.error, trace };
}
return { entries: run('entries'), values: run('values') };
},
'35_shallow_result': () => {
const shared = { n: 1 };
const o = { x: 1, shared };
const entries = Object.entries(o);
entries[0][1] = 7;
entries[1][1].n = 9;
return [o.x, o.shared.n, entries[1][1] === shared];
},
'36_setter_only': () => Object.entries({ set x(value) {} })
};
// Deliberately wrong replacements. Each side receives a fresh fixture.
const probes = {
W01_for_in: () => {
const wrong = [];
const o = inheritedFixture();
for (const k in o) wrong.push([k, o[k]]);
return { correct: Object.entries(inheritedFixture()), wrong };
},
W02_names_without_filter: () => {
const o = hiddenFixture();
return { correct: Object.entries(hiddenFixture()),
wrong: Object.getOwnPropertyNames(o).map(k => [k, o[k]]) };
},
W03_reflect_without_filter: () => {
const make = () => ({ visible: 1, [Symbol('s')]: 2 });
return { correct: Object.keys(make()), wrong: Reflect.ownKeys(make()).map(String) };
},
W04_lexical_sort: () => ({
correct: Object.keys({ 10: 10, 2: 2 }),
wrong: Object.keys({ 10: 10, 2: 2 }).sort()
}),
W05_length_loop: () => {
const a = [, , 'C'];
const wrong = [];
for (let i = 0; i < a.length; i++) wrong.push(a[i]);
return { correct: Object.values([, , 'C']), wrong };
},
W06_keys_then_map: () => {
const o = hideLaterFixture();
return { correct: Object.entries(hideLaterFixture()),
wrong: Object.keys(o).map(k => [k, o[k]]) };
},
W07_null_fallback: () => {
const wrong = o => Object.entries(o || {});
return { correct: capture(() => Object.entries(null)), wrong: wrong(null) };
},
W08_entries_for_keys: () => ({
correct: Object.keys(throwFixture()),
wrong: capture(() => Object.entries(throwFixture()).map(([key]) => key))
})
};
assert.deepEqual(Object.keys(cases), Object.keys(expected.cases));
assert.deepEqual(Object.keys(probes), Object.keys(expected.probes));
console.log(JSON.stringify({ node: process.version, execArgv: process.execArgv,
functionThisIsUndefined: (function () { return this; })() === undefined,
oracleSha256: freeze.sha256 }));
const actual = { cases: {}, probes: {} };
for (const [id, run] of Object.entries(cases)) {
actual.cases[id] = normalize(run());
assert.deepEqual(actual.cases[id], expected.cases[id], id);
console.log('PASS ' + id);
}
for (const [id, run] of Object.entries(probes)) {
actual.probes[id] = normalize(run());
assert.deepEqual(actual.probes[id], expected.probes[id], id);
assert.notDeepEqual(actual.probes[id].correct, actual.probes[id].wrong, id);
console.log('REJECT ' + id);
}
if (process.env.ACTUAL_FILE) {
fs.writeFileSync(process.env.ACTUAL_FILE, JSON.stringify(actual, null, 2) + '\n');
}
console.log('PASS 36 cases; REJECT 8 wrong wrappers');如果还要复核严格模式,将下面代码保存为同一目录中的 public-strict.cjs,然后运行 node --use-strict public-strict.cjs。执行器只为这份本地测试源加上显式严格指令,不应拿它执行不可信输入。
const fs = require('node:fs');
const path = require('node:path');
const source = fs.readFileSync(path.join(__dirname, 'public-tests.cjs'), 'utf8');
// Compile the same trusted local test source with an explicit strict directive.
// This runner is for these tests, not for evaluating untrusted input.
const execute = new Function('require', '__dirname', '"use strict";\n' + source);
execute(require, __dirname);实际运行结果与验证范围
预期 JSON 在北京时间 2026 年 10 月 22 日 06:43:34 冻结,第一次行为测试开始于 06:44:37。冻结后的 SHA-256 为 415a6655f27167ec0d3b3e2190787c54909318dece5283d26f981db2804cccde;测试后没有为了配合输出修改预期。
本机 Node.js v24.19.0 的普通 CommonJS 执行中,functionThisIsUndefined 为 false。仅添加 --use-strict 再执行 CommonJS 入口时,这个探针仍是 false,所以不能仅凭参数就声称已经测试了严格模式。随后使用显式 "use strict" 指令执行同一份测试源,探针为 true;三次运行均通过 36 组用例,并拒绝全部 8 个错误包装。公开自包含版本也按这三种入口复跑,结果相同。
// Normal CommonJS entry: functionThisIsUndefined = false // CommonJS entry with --use-strict: functionThisIsUndefined = false // Explicit directive runner with --use-strict: functionThisIsUndefined = true // Each run ends with: PASS 36 cases; REJECT 8 wrong wrappers
这些结果说明所列合成输入与手推预期一致,不代表完整的跨引擎符合性认证,也不包含宿主对象、代理对象、性能或兼容性矩阵测试。36 是分组用例数量,并不是断言次数。
选择接口时的实用检查
只需要名字就用 Object.keys;需要键和值的对应关系时用 Object.entries;只消费值时用 Object.values。
需要包含 Symbol 或不可枚举属性时,先重新定义需求,再选择其他反射接口,不要悄悄扩大枚举范围。
要按业务顺序展示字段时,显式维护顺序或排序规则,别把对象枚举顺序当成任意业务排序。
对可能含 getter 的对象,先考虑读取是否会改变状态或抛错。不要用“只是转成数组”来推断过程没有副作用。
需要深层隔离时,另行选择满足数据类型与副作用约束的复制方案;entries 本身不提供深拷贝保证。
本文依据当前在线 ECMAScript 算法与 MDN 文档核对接口语义,并用独立合成样例实测。来源核验日期为北京时间 2026 年 10 月 22 日;没有把这些既有接口描述成当天发布的新功能。


