返回任意次数的字符串的最佳或最简洁的方法是什么?
以下是我目前为止拍得最好的照片:
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('');
}
当前回答
适用于所有浏览器
这是最简洁的:
function repeat(s, n) { return new Array(n+1).join(s); }
如果你也关心性能,这是一个更好的方法:
function repeat(s, n) { var a=[],i=0;for(;i<n;)a[i++]=s;return a.join(''); }
如果要比较这两个选项的性能,请参阅此Fiddle和此Fiddle以获得基准测试。在我自己的测试中,第二个选项在Firefox中大约快2倍,在Chrome中大约快4倍!
仅适用于现代浏览器:
在现代浏览器中,你现在也可以这样做:
function repeat(s,n) { return s.repeat(n) };
这个选项不仅比其他两个选项都要短,而且比第二个选项还要快。
不幸的是,它不能在任何版本的ie浏览器中运行。表中的数字指定了完全支持该方法的第一个浏览器版本:
其他回答
新读者注意:这个答案很老,而且不太实用——它只是“聪明”,因为它使用Array的东西来获取 串事情做完了。当我写“更少的过程”时,我肯定是指 “更少的代码”,因为,正如其他人在随后的回答中指出的那样,它 表演像猪一样。所以如果你看重速度就不要用它。
我将把这个函数直接放到String对象上。与其创建一个数组,填充它,然后用一个空字符连接它,不如创建一个适当长度的数组,然后用你想要的字符串连接它。同样的结果,更少的过程!
String.prototype.repeat = function( num )
{
return new Array( num + 1 ).join( this );
}
alert( "string to repeat\n".repeat( 4 ) );
要在指定次数内重复一个字符串,可以使用JavaScript中内置的repeat()方法。
下面是一个重复以下字符串4次的例子:
const name = "king";
const repeat = name.repeat(4);
console.log(repeat);
输出:
"kingkingkingking"
或者我们可以创建自己版本的repeat()函数,如下所示:
function repeat(str, n) {
if (!str || !n) {
return;
}
let final = "";
while (n) {
final += s;
n--;
}
return final;
}
console.log(repeat("king", 3))
(最初发布于https://reactgo.com/javascript-repeat-string/)
这是JSLint的安全版本
String.prototype.repeat = function (num) {
var a = [];
a.length = num << 0 + 1;
return a.join(this);
};
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/
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