2024年9月9日 星期一

初探 Intl.ListFormat()

 初探 Intl.ListFormat()

前言

  在書寫文章時,有多個選項時會書寫成"A、B與C"這項的格式 ,Intl.ListFormat() 可以依據不同的地區提供此格式,在此把學習過程做個紀錄。


內容

  範例如下

const itemList = ['A', 'B', 'C' , 'D' ];

console.log( new Intl.ListFormat('en', {
  style: 'long',
  type: 'conjunction',
}).format(itemList) );//A, B, C, and D
//
console.log( new Intl.ListFormat('zh-TW', {
  style: 'long',
  type: 'conjunction',
}).format(itemList) );//A、B、C和D
//
console.log( new Intl.ListFormat('zh-TW', {
  style: 'long',
  type: 'disjunction',
}).format(itemList) );//A、B、C或D
//
console.log( new Intl.ListFormat('zh-TW', {
  style: 'long',
  type: 'unit',
}).format(itemList) );//A B C D


Intl.ListFormat() 是用來顯示陣列的內容,讓內容可以符合當地的文法書寫,第一例顯示是以 en 來示範,可以看到顯示的結果是 A, B, C, and D ,最後兩個項目會插入一個 and ,接著把區域改成 zh-TW 得到的結果是 A、B、C 和 D ,最後兩個選項會插入"和",選項間的符號也變成 、  ,參數的 type 還可以是 disjunction 與 unit ,當輸入 disjunction  後,最後兩個項目插入會變成"或",當樹入 unit ,最後兩個選項就不再插入字,項目間會是用"空白"隔開,可以理解就只是單純的個別顯示。


參考資料

[ developer.mozilla.org ] Intl.ListFormat

沒有留言:

張貼留言