Object Keys Order Puts Integers First
Show that integer-like keys sort numerically before string keys, which follow insertion order, and that JSON.stringify keeps the same order.
Code
// 类整数键(integer keys)按数值升序排最前,字符串键按插入顺序
const events = {
10: 'restart',
2: 'boot',
name: 'worker',
1: 'init',
role: 'server',
};
console.log('Object.keys:', Object.keys(events).join(','));
console.log('JSON order:', JSON.stringify(events));
// 想保持插入顺序时:改用 Map,它按写入顺序遍历一切键
const ordered = new Map([
[10, 'restart'],
[2, 'boot'],
['name', 'worker'],
]);
console.log('Map order:', [...ordered.keys()].join(','));How the snippet works
Module-level bindings hold the data — events, ordered — with no function scope in between.
Module-level object literal, fixed keys: name, role.
Applying it
Running the file prints labeled results such as Object.keys:, JSON order:, Map order: — each operation’s effect is visible in the output.
Statements that matter
const ordered = new Map([
[10, 'restart'],
[2, 'boot'],
['name', 'worker'],
]);
Interactive Tools for This Topic
FAQ
- Any setup needed beyond the language runtime?
- None — the language runtime is the only requirement. Its state lives in module-level bindings: `events`, `ordered`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.