Intl.ListFormat.prototype.formatToParts()
formatToParts() 方法的 Intl.ListFormat 例項返回一個物件陣列,這些物件表示由 format() 返回的格式化字串的每個部分。這對於根據本地化特定的令牌構建自定義字串很有用。
試一試
const vehicles = ["Motorcycle", "Bus", "Car"];
const formatterEn = new Intl.ListFormat("en", {
style: "long",
type: "conjunction",
});
const formatterFr = new Intl.ListFormat("fr", {
style: "long",
type: "conjunction",
});
const partValuesEn = formatterEn.formatToParts(vehicles).map((p) => p.value);
const partValuesFr = formatterFr.formatToParts(vehicles).map((p) => p.value);
console.log(partValuesEn);
// Expected output: "["Motorcycle", ", ", "Bus", ", and ", "Car"]"
console.log(partValuesFr);
// Expected output: "["Motorcycle", ", ", "Bus", " et ", "Car"]"
語法
js
formatToParts(list)
引數
list-
一個可迭代物件,例如 Array,包含字串。省略它將格式化空陣列,這可能會造成一些困惑,因此建議始終顯式傳遞列表。
返回值
一個物件 Array,包含格式化列表的各個部分。每個物件有兩個屬性:type 和 value,它們都包含一個字串。按提供順序連線 value 字串將得到與 format() 相同的字串。type 可以是以下之一:
示例
使用 formatToParts()
js
const fruits = ["Apple", "Orange", "Pineapple"];
const myListFormat = new Intl.ListFormat("en-GB", {
style: "long",
type: "conjunction",
});
console.table(myListFormat.formatToParts(fruits));
// [
// { "type": "element", "value": "Apple" },
// { "type": "literal", "value": ", " },
// { "type": "element", "value": "Orange" },
// { "type": "literal", "value": " and " },
// { "type": "element", "value": "Pineapple" }
// ]
規範
| 規範 |
|---|
| ECMAScript® 2026 國際化 API 規範 # sec-Intl.ListFormat.prototype.formatToParts |
瀏覽器相容性
載入中…