# generaltranslation: General Translation Core SDK: formatListToParts URL: https://generaltranslation.com/zh/docs/core/functions/formatting/format-list-to-parts.mdx --- title: formatListToParts description: 可独立使用的函数,用于将列表格式化为多个部分,同时保留原始类型 --- ## 概述 独立的 `formatListToParts` 函数无需 GT 实例,即可将数组格式化为特定于区域设置的各个部分。 它会在各项之间插入字符串分隔符,同时保留每个元素的原始类型,并返回 `Array`。 ```typescript import { formatListToParts } from 'generaltranslation'; const parts = formatListToParts(['red', 'green', 'blue'], { locales: ['es'], type: 'disjunction' }); // 返回: ['red', ', ', 'green', ' o ', 'blue'] ``` ## 参考 ### 参数 | 名称 | 类型 | 说明 | | --------- | ---------------------------------------------------------- | --------------------- | | `array` | `Array` | 要格式化的元素数组 | | `options` | `ListFormatPartsOptions & { locales: string \| string[] }` | 包含必填 `locales` 的格式化配置 | ### ListFormatPartsOptions | 名称 | 类型 | 描述 | | --------- | ------------------------------------------ | ------------------------------ | | `locales` | `string \| string[]` | **必填** - 格式化时使用的区域设置 | | `type?` | `'conjunction' \| 'disjunction' \| 'unit'` | 列表格式化类型 (默认值:`'conjunction'`) | | `style?` | `'long' \| 'short' \| 'narrow'` | 列表格式化样式 (默认值:`'long'`) | ### 返回 `Array` - 一个数组,其中原始项与特定于区域设置的字符串分隔符交错排列。 *** ## 示例 ### 基本用法 ```typescript copy import { formatListToParts } from 'generaltranslation'; // 连接列表 console.log(formatListToParts(['A', 'B', 'C'], { locales: 'en' })); // 输出:['A', ', ', 'B', ', and ', 'C'] // 析取列表 console.log(formatListToParts(['A', 'B', 'C'], { locales: 'en', type: 'disjunction' })); // 输出:['A', ', ', 'B', ', or ', 'C'] ``` ### 混合类型数组 ```typescript copy // 数字和对象会被保留 console.log(formatListToParts(['apple', 42, { type: 'fruit' }], { locales: 'en' })); // 输出:['apple', ', ', 42, ', and ', { type: 'fruit' }] ``` ### 特定于区域设置的格式 ```typescript copy // 西班牙语析取 console.log(formatListToParts(['red', 'green', 'blue'], { locales: 'es', type: 'disjunction' })); // 输出:['red', ', ', 'green', ' o ', 'blue'] // 短格式 console.log(formatListToParts(['first', 'second'], { locales: 'en', style: 'short' })); // 输出:['first', ' & ', 'second'] ``` *** ## 注意事项 * 与 GT 类方法不同,`locales` 参数是必填项 * 会保留原始条目类型——仅在元素之间插入字符串分隔符 * 这是它与 `formatList` 的关键区别,后者返回的是一个扁平的 `string` * 特别适合在 React 等 UI 框架中渲染混合类型数组 * 它使用的底层 `Intl.ListFormat` 与 GT 类方法相同 ## 后续步骤 * 查阅 [`Intl.ListFormat` documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat) 文档,了解更多选项 * 如需独立的数字格式化,请参阅 [`formatNum`](/docs/core/functions/formatting/format-num) * 如需独立的日期格式化,请参阅 [`formatDateTime`](/docs/core/functions/formatting/format-date-time) * 如需了解基于实例的用法,请参阅 GT 类的 [`formatListToParts`](/docs/core/class/methods/formatting/format-list-to-parts)