返回任意次数的字符串的最佳或最简洁的方法是什么?
以下是我目前为止拍得最好的照片:
function repeat(s, n){
var a = [];
while(a.length < n){
a.push(s);
}
return a.join('');
}
返回任意次数的字符串的最佳或最简洁的方法是什么?
以下是我目前为止拍得最好的照片:
function repeat(s, n){
var a = [];
while(a.length < n){
a.push(s);
}
return a.join('');
}
当前回答
/**
@desc: repeat string
@param: n - times
@param: d - delimiter
*/
String.prototype.repeat = function (n, d) {
return --n ? this + (d || '') + this.repeat(n, d) : '' + this
};
这是如何重复字符串多次使用delimeter。
其他回答
disfated的答案提高了5-7%。
通过在计数> 1处停止来展开循环,并在循环之后执行额外的result += pattnern concat。这将避免循环最终使用以前未使用的模式+=模式,而不必使用昂贵的if检查。 最终的结果是这样的:
String.prototype.repeat = function(count) {
if (count < 1) return '';
var result = '', pattern = this.valueOf();
while (count > 1) {
if (count & 1) result += pattern;
count >>= 1, pattern += pattern;
}
result += pattern;
return result;
};
下面是disfate的小提琴分叉的展开版本:http://jsfiddle.net/wsdfg/
小提琴:http://jsfiddle.net/3Y9v2/
function repeat(s, n){
return ((new Array(n+1)).join(s));
}
alert(repeat('R', 10));
String.prototype.repeat现在是ES6标准。
'abc'.repeat(3); //abcabcabc
/**
@desc: repeat string
@param: n - times
@param: d - delimiter
*/
String.prototype.repeat = function (n, d) {
return --n ? this + (d || '') + this.repeat(n, d) : '' + this
};
这是如何重复字符串多次使用delimeter。
ES-Next有很多方法
1. ES2015/ES6已经实现了这个repeat()方法!
/** * str: String * count: Number */ const str = `hello repeat!\n`, count = 3; let resultString = str.repeat(count); console.log(`resultString = \n${resultString}`); /* resultString = hello repeat! hello repeat! hello repeat! */ ({ toString: () => 'abc', repeat: String.prototype.repeat }).repeat(2); // 'abcabc' (repeat() is a generic method) // Examples 'abc'.repeat(0); // '' 'abc'.repeat(1); // 'abc' 'abc'.repeat(2); // 'abcabc' 'abc'.repeat(3.5); // 'abcabcabc' (count will be converted to integer) // 'abc'.repeat(1/0); // RangeError // 'abc'.repeat(-1); // RangeError
2. ES2017/ES8新增String.prototype.padStart()
Const STR = 'abc '; Const times = 3; const newStr = str. padstartlength * times, str.toUpperCase()); console.log(' newStr = ', newStr); // "newStr =" "ABC ABC ABC "
3.ES2017/ES8新增String.prototype.padEnd()
Const STR = 'abc '; Const times = 3; const newStr = str. padend (str。length * times, str.toUpperCase()); console.log(' newStr = ', newStr); // "newStr =" "abc abc abc "
refs
http://www.ecma-international.org/ecma-262/6.0/#sec-string.prototype.repeat
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd