标签:分享 ast repeat 展示 pad blob 方法 star arc
背景:
var t = new Date().getMonth() + 1;
// t ===> 7,没有0,怎么展示成下面的样子?
// 2018-07-23
解决上述问题的一个思路:
// 补0函数
function(num) {
return +num < 10 ? '0' + num : num;
}
padStart(len, str)
栗子:
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
实现的思路:
var a = '22'
a.padStart(len, str)
伪代码:
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参数一样,只是把想加的字符串加到后头。
var a = 'aaa'.padEnd(15, {});
// aaa[object Obje
兼容性:
目前来看用于前端需要兼容,请看:string.polyfill.js
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支持到版本8
标签:分享 ast repeat 展示 pad blob 方法 star arc
原文地址:https://www.cnblogs.com/hongrunhui/p/9370954.html