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.
Code
// 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-reportWhat 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
Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Indentation ConverterConvert leading indentation between tabs and spaces at a chosen width, leaving inner content untouched.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.