# generaltranslation: General Translation Core SDK: formatListToParts URL: https://generaltranslation.com/zh/docs/core/class/methods/formatting/format-list-to-parts.mdx --- title: formatListToParts description: formatListToParts 方法的 API 参考,用于将列表格式化为多个部分,同时保留原始类型 --- ## 概述 `formatListToParts` 方法会将数组格式化为特定于区域设置的多个部分,在各项之间插入字符串分隔符,同时保留每个元素的原始类型。 与返回单一字符串的 `formatList` 不同,此方法返回 `Array`,因此非常适合包含字符串、数字、对象或 JSX 元素的混合类型数组。 ```typescript const gt = new GT({ locales: ['en'] }); const parts = gt.formatListToParts(['apple', 42, { type: 'fruit' }]); // 返回: ['apple', ', ', 42, ', and ', { type: 'fruit' }] ``` ## 参考 ### 参数 | 名称 | 类型 | 描述 | | ---------- | ------------------------ | --------- | | `array` | `Array` | 要格式化的元素数组 | | `options?` | `ListFormatPartsOptions` | 可选的格式设置 | ### ListFormatPartsOptions 在 `Intl.ListFormatOptions` 的基础上进行了扩展,支持额外指定区域设置: | 名称 | 类型 | 说明 | | ---------- | ------------------------------------------ | ------------------------------ | | `locales?` | `string \| string[]` | 覆盖格式化时使用的区域设置 (默认为实例的区域设置) | | `type?` | `'conjunction' \| 'disjunction' \| 'unit'` | 列表格式化类型 (默认值:`'conjunction'`) | | `style?` | `'long' \| 'short' \| 'narrow'` | 列表格式化样式 (默认值:`'long'`) | ### 返回值 `Array` - 由原始项与特定于区域设置的字符串分隔符交错组成的数组。 *** ## 示例 ### 基本列表格式 ```typescript copy import { GT } from 'generaltranslation'; const gt = new GT({ locales: ['en'] }); // 连接(默认)— "and" 列表 console.log(gt.formatListToParts(['A', 'B', 'C'])); // 输出:['A', ', ', 'B', ', and ', 'C'] // 析取 — "or" 列表 console.log(gt.formatListToParts(['A', 'B', 'C'], { type: 'disjunction' })); // 输出:['A', ', ', 'B', ', or ', 'C'] ``` ### 混合类型数组 ```typescript copy // 数字和对象会被保留 console.log(gt.formatListToParts(['apple', 42, { type: 'fruit' }])); // 输出:['apple', ', ', 42, ', and ', { type: 'fruit' }] ``` ### 样式变体 ```typescript copy // 短格式 console.log(gt.formatListToParts(['first', 'second'], { style: 'short' })); // 输出:['first', ' & ', 'second'] // 单位格式 console.log(gt.formatListToParts(['1km', '2mi'], { type: 'unit' })); // 输出:['1km', ', ', '2mi'] ``` ### 特定于区域设置的格式设置 ```typescript copy // 西班牙语析取 console.log(gt.formatListToParts(['red', 'green', 'blue'], { locales: ['es'], type: 'disjunction' })); // 输出:['red', ', ', 'green', ' o ', 'blue'] ``` *** ## 说明 * 原始项类型会保留——只会在元素之间插入字符串分隔符 * 这是它区别于 `formatList` 的关键之处,后者会返回一个扁平的 `string` * 这在 React 等 UI 框架中渲染混合类型数组时尤其有用 * 该方法底层使用浏览器原生的 `Intl.ListFormat` * `type: 'conjunction'` 会生成 “and” 列表,`'disjunction'` 会生成 “or” 列表,而 `'unit'` 会生成单位样式的列表 ## 后续步骤 * 查看 [`Intl.ListFormat` 文档](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat) 以了解更多选项 * 数字格式化请参阅 [`format-num`](/docs/core/class/methods/formatting/format-num) * 如需在不创建 GT 实例的情况下使用,请参阅独立的 [`format-list-to-parts`](/docs/core/functions/formatting/format-list-to-parts) * 使用列表插值进行消息格式化,请参阅 [`format-message`](/docs/core/class/methods/formatting/format-message)