实现说明
rebuilt 定义在模块顶层,中间不经过函数作用域。
常见问题
运行时需要 npm、pip、cargo 之类帮忙吗?
不需要——包管理器在这里无事可做,没有任何声明。 跨调用保留的状态放在这些顶层绑定里:rebuilt。
核心语句
const rebuilt = new Map(entries);
const stock: ReadonlyMap<string, number> = new Map([
['coffee', 320],
['tea', 280],
['cocoa', 450],
]);
代码示例
const stock: ReadonlyMap<string, number> = new Map([
['coffee', 320],
['tea', 280],
['cocoa', 450],
]);
// entries() 展开成元组数组:可以像普通数组一样排序
const entries: ReadonlyArray<readonly [string, number]> = [...stock.entries()];
console.log(JSON.stringify(entries), 'sorted-by-value:', JSON.stringify([...entries].sort((a, b) => a[1] - b[1])));
// 元组数组重建 Map:键序按数组顺序重排,get 与 size 保持不变
const rebuilt = new Map(entries);
console.log(rebuilt.get('coffee'), rebuilt.size);