stringObject 之复制

stringObject.repeat(count)

repeat() 构造并返回一个新字符串,该字符串具有指定的字符串副本数量。

count参数
介于0和正无穷大之间的整数 : [0, +∞) 。表示在新构造的字符串中重复了多少遍原字符串。

RangeError: 重复次数不能为负数。
RangeError: 重复次数必须小于 infinity,且长度不会大于最长的字符串。

"abc".repeat(-1)     // RangeError: repeat count must be positive and less than inifinity
"abc".repeat(0)      // ""
"abc".repeat(1)      // "abc"
"abc".repeat(2)      // "abcabc"
"abc".repeat(3.5)    // "abcabcabc" 参数count将会被自动转换成整数.
"abc".repeat(1/0)    // RangeError: repeat count must be positive and less than inifinity

({toString : () => "abc", repeat : String.prototype.repeat}).repeat(2)   
//"abcabc",repeat是一个通用方法,也就是它的调用者可以不是一个字符串对象.

用处:数字格式化,为小数点后位数补齐

var FormatUtils = function(){
	//复制
	function _repeat(count, sep){
		if(count < 1){
			count = 0;
		}
		for(var buf = [], i = count; i--;){
			buf.push(this);
		}
		return buf.join(sep || '');
	}
	
	function _fotNum(len){
		if(len<= 0){
			len= 0;
		}
		else{
			len = '0.' + '0'.repeat(len);
		}
		return len;
	}
	
	return {
		repeat:_repeat,
		fotNum:_fotNum
	}
}(); 

//调用
console.log(FormatUtils.fotNum(3)) //0.000

你可能感兴趣的:(javascript)