背景:javascript
var t = new Date().getMonth() + 1; // t ===> 7,沒有0,怎麼展現成下面的樣子? // 2018-07-23
解決上述問題的一個思路:前端
// 補0函數 function(num) { return +num < 10 ? '0' + num : num; }
padStart(len, str)
java
栗子:node
var a = '7'; a.padStart(2, '0'); // a ===> 07
var b = 'hi'; b.padStart(10, 'hello'); // b ===> hellohelhi, 重複補充
var c = 'hi'; c.padStart(10, ''); // c ===> hi
var d = 'a'; d.padStart(5, false); // falsa d.padStart(5, []); // a d.padStart(5, {}); // [obja d.padStart(5, null); // nulla d.padStart(5, function(){}); // funca
實現的思路:git
var a = '22' a.padStart(len, str)
僞代碼:github
var res = '' if (str.toString) { res = str.toString(); } else { res = Object.prototype.toString.call(str); } return res;
res.repeat(len/2+1).slice(0, len - a.length) + a
padEnd()
和padStart參數同樣,只是把想加的字符串加到後頭。app
var a = 'aaa'.padEnd(15, {}); // aaa[object Obje
兼容性:函數
目前來看用於前端須要兼容,請看:string.polyfill.jsthis
if (!String.prototype.padStart) { String.prototype.padStart = function padStart(targetLength,padString) { targetLength = targetLength>>0; //truncate if number or convert non-number to 0; padString = String((typeof padString !== 'undefined' ? padString : ' ')); if (this.length > targetLength) { return String(this); } else { targetLength = targetLength-this.length; if (targetLength > padString.length) { padString += padString.repeat(targetLength/padString.length); //append to original to ensure we are longer than needed } return padString.slice(0,targetLength) + String(this); } }; }
node.js支持到版本8prototype