補白即格式化,例如將數字都輸出成兩位數,前面0補位學習
例子一:spa
for(let i = 1 ; i < 32 ; i++){ console.log(i >= 10 ? i : `0${i}`) } // 1-9輸出01-09 // 10-31正常輸出
用另外一個字符串填充當前字符串(若是須要的話,會重複屢次),從頭補白(也就是左側)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
用另外一個字符串填充當前字符串(若是須要的話,會重複屢次),從當前字符串的末尾(右側)開始填充。it
例子三的padEnd
寫法:console
for(let i = 1 ; i < 32000 ; i+=1000){ // 自動補全,能補幾位是幾位,而後從尾部輪詢繼續補到指定的長度 console.log(i.toString().padEnd(5, '*%$')) } // 1*%$* // 1001* // 2001* // ... // 10001 // 11001