实现说明
Intl.PluralRules.selectRange 为区间选复数形式以函数 formatRangeLabel为骨架。
使用要点
- 环境除了装好解释器或编译器,无需任何准备。
- 演示输出是带标签的(
en 0..1:、en 1..5:、fr 0..1:),每个操作都会留下自己的一行标注。
常见问题
这段代码会引入外部包吗?
不涉及外部包,每个调用都落在内建 API 上。 文件在加载时定义 formatRangeLabel。
主签名形如 function formatRangeLabel(rules, start, end, labels)
核心语句
return `${start}-${end} ${labels[category] ?? labels.other} (${category})`;
const enRules = new Intl.PluralRules('en-US');
const frRules = new Intl.PluralRules('fr-FR');
代码示例
const enRules = new Intl.PluralRules('en-US');
const frRules = new Intl.PluralRules('fr-FR');
function formatRangeLabel(rules, start, end, labels) {
const category = rules.selectRange(start, end);
return `${start}-${end} ${labels[category] ?? labels.other} (${category})`;
}
const enLabels = { one: 'item', other: 'items' };
const frLabels = { one: 'article', other: 'articles' };
// In English 0-1 selects 'other', whereas in French 0-1 selects 'one'
console.log('en 0..1:', formatRangeLabel(enRules, 0, 1, enLabels));
console.log('en 1..5:', formatRangeLabel(enRules, 1, 5, enLabels));
console.log('fr 0..1:', formatRangeLabel(frRules, 0, 1, frLabels));
console.log('fr 1..5:', formatRangeLabel(frRules, 1, 5, frLabels));