ES8(三) —— String Padding

目錄

  • 對String補白的方式
  • padStart
  • padEnd
  • ES6-ES10學習版圖

ES5對String補白的方式

補白即格式化,例如將數字都輸出成兩位數,前面0補位學習

例子一:spa

for(let i = 1 ; i < 32 ; i++){
  console.log(i >= 10 ? i : `0${i}`)
}
// 1-9輸出01-09
// 10-31正常輸出

padStart

用另外一個字符串填充當前字符串(若是須要的話,會重複屢次),從頭補白(也就是左側)code

  • 第一個參數是目標長度,要輸出的位數
  • 第二個參數是佔位內容,默認是空格
  • 返回值是生成的新的字符串

例子一的padStart寫法:blog

for(let i = 1 ; i < 32 ; i++){
  // 目標是2位數,不夠的用0補齊
  console.log(i.toString().padStart(2, '0'))
}
// 1-9輸出01-09
// 10-31正常輸出

例子二:1到320,階梯是10rem

for(let i = 1 ; i < 320 ; i+=10){
  //指定補2位,不夠的加0,超出的無論
  console.log(i.toString().padStart(2, '0')) // 輸出1是01,11是11,101是101
  //指定補3位
  console.log(i.toString().padStart(3, '0')) // 輸出1是001,11是011,101是101
}

例子三:1到32000,梯度1000字符串

for(let i = 1 ; i < 32000 ; i+=1000){
  // 自動補全,能補幾位是幾位,而後從頭輪詢繼續補到指定的長度
  console.log(i.toString().padStart(5, '*%$'))
}
// *%$*1
// *1001
// *2001
// ...
// 10001
// 11001

padEnd

用另外一個字符串填充當前字符串(若是須要的話,會重複屢次),從當前字符串的末尾(右側)開始填充。it

  • 第一個參數是目標長度,要輸出的位數
  • 第二個參數是佔位內容,默認是空格
  • 返回值是生成的新的字符串

例子三的padEnd寫法:console

for(let i = 1 ; i < 32000 ; i+=1000){
// 自動補全,能補幾位是幾位,而後從尾部輪詢繼續補到指定的長度
  console.log(i.toString().padEnd(5, '*%$'))
}
// 1*%$*
// 1001*
// 2001*
// ...
// 10001
// 11001

ES6-ES10學習版圖

ES6-10.png

相關文章
相關標籤/搜索