← 中文资源

简体中文版本

Intl.ListFormat 渲染自然列表

Intl.ListFormat 把数组渲染成符合语言习惯的列表:and/or 连接词、narrow 紧凑形态、formatToParts 拿到底层分段自定义样式,不再手写逗号拼接。

阅读英文原文

运行结果

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

long   : parse-args, run-pipeline, and write-report
or     : json, yaml, or toml
narrow : 3 files 2 warnings
parts  : parse-args[,]run-pipeline[, and]write-report

实现说明

stages、and、or、unit 定义在模块顶层,中间不经过函数作用域。

使用要点

  • 演示输出是带标签的(narrow :),每个操作都会留下自己的一行标注。

常见问题

运行时需要 npm、pip、cargo 之类帮忙吗?

不需要——包管理器在这里无事可做,没有任何声明。 状态都挂在模块顶层:stages、and、or。

核心语句

.map((part) => (part.type === 'literal' ? `[${part.value.trim()}]` : part.value))
.join('');
const and = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' });
const or = new Intl.ListFormat('en', { style: 'long', type: 'disjunction' });

代码示例

// Intl.ListFormat: 把数组渲染成符合语言习惯的列表文案
const stages = ['parse-args', 'run-pipeline', 'write-report'];

// conjunction(long 风格): "a, b, and c"
const and = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' });
console.log('long   :', and.format(stages));

// disjunction: "a, b, or c"——错误提示里列举可选值
const or = new Intl.ListFormat('en', { style: 'long', type: 'disjunction' });
console.log('or     :', or.format(['json', 'yaml', 'toml']));

// narrow + unit: 空间紧张时的紧凑形态
const unit = new Intl.ListFormat('en', { style: 'narrow', type: 'unit' });
console.log('narrow :', unit.format(['3 files', '2 warnings']));

// formatToParts: 拿到底层分段,自定义包裹样式
const marked = and
  .formatToParts(stages)
  .map((part) => (part.type === 'literal' ? `[${part.value.trim()}]` : part.value))
  .join('');
console.log('parts  :', marked);