函数:给值挑一种本地化形式
占位符里给操作数加上 :函数名 就调用一个函数:{$count :number}、{$d :date length=long}。函数有两种职责——格式化(把值变成本地化字符串)与选择(在
.match 里决定走哪个变体)。本页只看格式化,选择见 match 页。选项用 name=value 跟在函数名后,值可以是字面量或 $变量。
REQUIRED vs DRAFT。规范把内置函数分两档:REQUIRED(:string / :number / :integer / :offset)任何实现都得有;DRAFT(:date / :time / :datetime / :currency /
:unit / :percent)仍可能变动,在 messageformat 包里需显式 { functions: DraftFunctions } 注册——本系列已替你开好,故都能直接用。
1 · 全部内置函数一览
| 函数 | 档位 | 操作数 | 关键 options | 可选择? |
|---|---|---|---|---|
:string |
REQUIRED | 任意 (转字符串) | — | ✓ 按字面相等 |
:number |
REQUIRED | 数字 / BigInt / 数字串 | minimum/maximumFractionDigits、minimumIntegerDigits、signDisplay、useGrouping、select、roundingMode… | ✓ 复数 / 序数 / 精确 |
:integer |
REQUIRED | 数字 (取整) | minimumIntegerDigits、signDisplay、select… | ✓ |
:offset |
REQUIRED | 数字 | add、subtract | ✓ |
:date |
DRAFT | Date / 时间戳 / 日期串 | fields、length、calendar、timeZone | — |
:time |
DRAFT | 同上 | precision、timeZoneStyle、hour12 | — |
:datetime |
DRAFT | 同上 | dateFields、dateLength、timePrecision、timeZoneStyle、hour12 | — |
:currency |
DRAFT | 数字 | currency(必填)、currencyDisplay、currencySign、fractionDigits | — |
:unit |
DRAFT | 数字 | unit(必填)、unitDisplay、signDisplay | — |
:percent |
DRAFT | 数字 (0.25→25%) | maximumFractionDigits… | ✓ |
2 · 动手试:每个函数都跑一遍
选函数、调操作数与选项,实时看消息源、成品、以及 formatToParts() 的拆解:
3 · 同一个值,跨 locale
函数最大的价值是本地化:同样的源与值,换 locale 自动变形。
函数也能挂在字面量上。操作数不一定是变量:{1234.5 :currency currency=JPY} 直接格式化一个常量。这在写「固定模板里嵌一个定值」时很方便,也是测试函数行为最快的方式。