初探 Intl.ListFormat.formatToParts()
前言
在先前的 初探 Intl.ListFormat() 使用 Intl.ListFormat.format() 來輸出結果,Intl.ListFormat 還支援另一種輸出,也就是 Intl.ListFormat.formatToParts() ,在此把學習的過程做個紀錄。
內容
範例如下
const itemList = ['A', 'B', 'C' , 'D' ];
//
let parts = new Intl.ListFormat('en', {
style: 'long',
type: 'conjunction',
}).formatToParts(itemList);
console.log(parts);
// [[object Object] {
// type: "element",
// value: "A"
// }, [object Object] {
// type: "literal",
// value: ", "
// }, [object Object] {
// type: "element",
// value: "B"
// }, [object Object] {
// type: "literal",
// value: ", "
// }, [object Object] {
// type: "element",
// value: "C"
// }, [object Object] {
// type: "literal",
// value: ", and "
// }, [object Object] {
// type: "element",
// value: "D"
// }]
partValues = parts.map((p) => p.value);
console.log(partValues);//["A", ", ", "B", ", ", "C", ", and ", "D"]
Intl.ListFormat.formatToParts() 的功用和之前的 初探 Intl.NumberFormat.formatToParts() 差不多,都是把結果切成很多的物件,如同範例的 parts 一樣,如果要提取每個物件的 value 的話,透過 Array.map() 就可以輸出包含每個 value 的陣列。
參考資料
[ developer.mozilla.org ] Intl.ListFormat.formatToParts()
沒有留言:
張貼留言