Intl.ListFormat Renders Arrays As Lists

Render arrays as natural list text with Intl.ListFormat: long conjunction and disjunction styles, a narrow unit style, and formatToParts for custom markup.

JavascriptCli Tooling

Code

javascriptsnippet
21 lines
// 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);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

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

What the code does

Top-level bindings stages, and, or, unit hold the demo state — nothing sits inside a function scope.

Applying it

The demo output is labeled (narrow :), so every printed line maps back to its originating operation.

Statements that matter

.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' });

Interactive Tools for This Topic

FAQ

Does the runtime need any help from npm, pip, cargo, or the like?
No — the package manager has nothing to do here; nothing is declared. Its state lives in module-level bindings: `stages`, `and`, `or`.