补白即格式化,例如将数字都输出成两位数,前面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