# Intl.ListFormat对象 根据语言环境进行列表格式化

> Intl 对象是 ECMAScript 国际化 API 的一个命名空间，它提供了精确的字符串对比、数字格式化，和日期时间格式化。下面这篇文章了解下关于Intl.ListFormat对象，针对列表元素进行数据格式化。

Author: DeathGhost
Published: 2021-03-05 19:38:55
Category: javascript
Canonical: https://www.deathghost.cn/article/javascript/91
Keywords: JavaScript, ECMAScript, Intl, Intl.ListFormat, ListFormat, 本地语言, 列表格式化, 数组元素格式化, 数组, 元素输出

Intl.ListFormat 是一个语言相关的列表格式化构造器。根据默认环境或指定语言项进行列表数据相应格式化输出。Web前端开发过程中通常会从后端获取相应的动态数据，但获取的数据需要将其格式转换后再输出于用户端方可。

Intl.ListFormat: ['苹果', '香蕉', '桃子'] 输出 我喜欢吃的水果是苹果、香蕉和桃子。

const formatter = new Intl.ListFormat();
const fruits = ['苹果', '香蕉', '桃子'];

console.log(`我喜欢吃的水果是${formatter.format(fruits)}。`);
// 我喜欢吃的水果是苹果、香蕉和桃子。

![Intl.ListFormat对象 根据语言环境进行列表格式化](https://www.deathghost.cn/public/upload/article/2021/03/05/1614949884945888.jpg)

Intl.ListFormat对象 根据语言环境进行列表格式化

关联文章&ldquo;[Intl.RelativeTimeFormat相对时间格式化](https://www.deathghost.cn/article/javascript/53)&rdquo;。

## 背景示例

例如从后端获取到一个对象。

['HTML', 'CSS', 'JavaScript', 'Angular']
需要将其格式化输出中文版

// 中文
// HTML、CSS、JavaScript和Angular
或英文版

// HTML, CSS, JavaScript, and Angular
通过一些方法（或引相关库），也可以将其转换，但比较麻烦，增加一定的捆绑，产生了一定的负影响（加载时间、解析/编译成本及其内存消耗等）。

这时，就可以启用Intl.ListFormat API进行本地列表格式化处理。

## Intl.ListFormat语法

new Intl.ListFormat([locales[, options]])

### 参数

locales 可选。符合 BCP 47 语言标注的字符串或字符串数组。

options 可选。 拥有下面所列属性中任意几个或全部的对象。

- localeMatcher 指定要使用的本地匹配算法。可选的值有"lookup" 和 "best fit"；默认情况下使用"best fit"。

- type 消息输出的格式。conjunction 默认值 &ldquo;且&rdquo; e.g.:  A, B, and C；disjunction "或" A, B, or C ，以及用于替代带计量单位的值列表的"unit" (例如： 5 pounds, 12 ounces)。

- style 被格式化消息的长度。可选值有："long" (默认值，例如： A, B, and C)、"short" 或者 "narrow" (例如： A, B, C)。 当style 的值为narrow时，type 属性的值只能取值unit。

例如本地环境默认不配置相应参数（环境默认中文）

const lf = new Intl.ListFormat();
lf.format(['HTML', 'CSS', 'JavaScript', 'Angular']);
// 结果输出：HTML、CSS、JavaScript和Angular
数组元素以&ldquo;顿号&rdquo;分隔，最后一项则是&ldquo;和&rdquo;。

如果要显示英文格式，则：

const lf = new Intl.ListFormat('en');
lf.format(['HTML', 'CSS', 'JavaScript', 'Angular']);
// 结果：HTML, CSS, JavaScript, and Angular
则以&ldquo;逗号&rdquo;和&ldquo;and&rdquo;输出。

若以中文语言输出&ldquo;或&rdquo;，则设置type为disjunction即可，默认是conjunction。如：

const lf = new Intl.ListFormat('zh', {
  type: 'disjunction'
});
lf.format(['HTML', 'CSS', 'JavaScript', 'Angular']);

// 结果输出：HTML、CSS、JavaScript或Angular
英文相应以&ldquo;or&rdquo;连接。

const lf = new Intl.ListFormat('en', {
  type: 'disjunction'
});
lf.format(['HTML', 'CSS', 'JavaScript', 'Angular']);

// 输出：HTML, CSS, JavaScript, or Angular

## 结尾

所以，既然出来了，在实际Web开发中将其运用起来，现代浏览器基本支持。它的出现，一方面是便于Web开发人员，更重要的是提高加载性能以及解析时和编译时性能。

## Related

- Previous: [剪贴板 navigator.clipboard API 异步读写](https://www.deathghost.cn/article/javascript/89)
- Next: [告别低精度累加：JavaScript Math.sumPrecise() 完全解析](https://www.deathghost.cn/article/javascript/128)
