← 中文资源

简体中文版本

Intl.PluralRules.selectRange 为区间选复数形式

用 Intl.PluralRules.selectRange 根据起止数值与区域语法决定区间复数类别,避免只看上限数字导致 0-1 或 1-5 等范围标签单复数错配。

阅读英文原文

运行结果

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

en 0..1: 0-1 items (other)
en 1..5: 1-5 items (other)
fr 0..1: 0-1 article (one)
fr 1..5: 1-5 articles (other)

实现说明

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