实现说明
循环只出现在 for (const word of words) tally[word] = (tally[word] ?? 0) + 1;,它的每次迭代处理一个元素。
prices、rounded、flags、upper 定义在模块顶层,中间不经过函数作用域。
模块级对象字面量,键名固定:usd、eur、jpy。
常见问题
运行时需要 npm、pip、cargo 之类帮忙吗?
不需要——包管理器在这里无事可做,没有任何声明。 跨调用保留的状态放在这些顶层绑定里:prices、rounded、flags。
核心语句
for (const word of words) tally[word] = (tally[word] ?? 0) + 1;
代码示例
// Object.entries + Object.fromEntries: 键不变的值变换往返
const prices = { usd: 100, eur: 92, jpy: 15000 };
// entries 把对象变成 [key, value] 元组数组,变换后再组装回对象
const rounded = Object.fromEntries(
Object.entries(prices).map(([code, amount]) => [code, Math.round(amount * 1.1)]),
);
console.log(JSON.stringify(rounded));
// 键名归一化:统一转大写
const flags = { 'Cache-Control': 'no-store', Accept: 'application/json' };
const upper = Object.fromEntries(
Object.entries(flags).map(([key, value]) => [key.toUpperCase(), value]),
);
console.log(JSON.stringify(upper));
// 词频统计后按出现次数排序重建
const words = 'to be or not to be'.split(' ');
const tally: Record<string, number> = {};
for (const word of words) tally[word] = (tally[word] ?? 0) + 1;
const ranked = Object.fromEntries(
Object.entries(tally).sort((a, b) => b[1] - a[1]),
);
console.log(JSON.stringify(ranked));