← 中文资源

简体中文版本

Map entries 展开与重建往返

把 Map.entries() 展开成类型化元组数组即可排序、过滤,再用 new Map(数组) 重建:键序随数组顺序重排,get 与 size 不变。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

[["coffee",320],["tea",280],["cocoa",450]] sorted-by-value: [["tea",280],["coffee",320],["cocoa",450]]
320 3

实现说明

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);