初探 Intl.DurationFormat.formatToParts()
前言
這次來學習 Intl.DurationFormat.formatToParts() ,在此把學習的過程做個紀錄。
內容
範例如下
let duration = {
hours : 8,
minutes: 30,
seconds: 40,
};
//
let parts = new Intl.DurationFormat( "zh-TW" ,{ style:'long' }).formatToParts(duration);
console.log( parts );
//
// [[object Object] {
// type: "integer",
// unit: "hour",
// value: "8"
// }, [object Object] {
// type: "literal",
// unit: "hour",
// value: " "
// }, [object Object] {
// type: "unit",
// unit: "hour",
// value: "小時"
// }, [object Object] {
// type: "literal",
// value: " "
// }, [object Object] {
// type: "integer",
// unit: "minute",
// value: "30"
// }, [object Object] {
// type: "literal",
// unit: "minute",
// value: " "
// }, [object Object] {
// type: "unit",
// unit: "minute",
// value: "分鐘"
// }, [object Object] {
// type: "literal",
// value: " "
// }, [object Object] {
// type: "integer",
// unit: "second",
// value: "40"
// }, [object Object] {
// type: "literal",
// unit: "second",
// value: " "
// }, [object Object] {
// type: "unit",
// unit: "second",
// value: "秒"
// }]
//
partValues = parts.map((p) => p.value);
console.log(partValues);//["8", " ", "小時", " ", "30", " ", "分鐘", " ", "40", " ", "秒"]
Intl.DurationFormat.formatToParts() 可以把結果輸出成好幾個部分,這樣可以方便提取個別項目的資料,但原始輸出是個物件,跟其它的 formatToParts() 一樣,如果要直接提取 value 的話,一樣透過 Array.map() 就可以輸出包含每個 value 的陣列。
參考資料
[ developer.mozilla.org ] Intl.DurationFormat
沒有留言:
張貼留言