Ste*_*eve 573 javascript string character repeat
在Perl中,我可以使用以下语法多次重复一个字符:
$a = "a" x 10; // results in "aaaaaaaaaa"
Run Code Online (Sandbox Code Playgroud)
有没有一种简单的方法来实现这个Javascript?我显然可以使用一个函数,但我想知道是否有任何内置方法,或其他一些聪明的技术.
Jas*_*rff 1147
这些天来,该repeat字符串的方法来实现,几乎无处不在.(它不在Internet Explorer中.)因此,除非您需要支持旧版浏览器,否则您只需编写:
"a".repeat(10)
Run Code Online (Sandbox Code Playgroud)
之前repeat,我们使用过这个hack:
Array(11).join("a") // create string with 10 a's: "aaaaaaaaaa"
Run Code Online (Sandbox Code Playgroud)
(注意,长度为11的数组只能使用10"a",因为Array.join将参数放在数组元素之间.)
西蒙还指出,根据这个jsperf,似乎在Safari和Chrome(但不是Firefox)中通过简单地使用for循环附加多次重复一个字符会更快(虽然不那么简洁).
Sal*_*ali 294
在一个新的ES6和声中,你将有自然的方式来重复这样做.此外ES6现在只是实验性的,此功能已在Edge,FF,Chrome和Safari中提供
"abc".repeat(3) // "abcabcabc"
Run Code Online (Sandbox Code Playgroud)
当然,如果没有重复功能,你可以使用旧货 Array(n + 1).join("abc")
ken*_*bec 54
如果你重复自己很方便:
String.prototype.repeat = String.prototype.repeat || function(n){
n= n || 1;
return Array(n+1).join(this);
}
alert( 'Are we there yet?\nNo.\n'.repeat(10) )Run Code Online (Sandbox Code Playgroud)
Kon*_*rov 13
性能最佳的方式是https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat
简短版本如下.
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;
}
return result + pattern;
};
var a = "a";
console.debug(a.repeat(10));
Run Code Online (Sandbox Code Playgroud)
来自Mozilla的Polyfill:
if (!String.prototype.repeat) {
String.prototype.repeat = function(count) {
'use strict';
if (this == null) {
throw new TypeError('can\'t convert ' + this + ' to object');
}
var str = '' + this;
count = +count;
if (count != count) {
count = 0;
}
if (count < 0) {
throw new RangeError('repeat count must be non-negative');
}
if (count == Infinity) {
throw new RangeError('repeat count must be less than infinity');
}
count = Math.floor(count);
if (str.length == 0 || count == 0) {
return '';
}
// Ensuring count is a 31-bit integer allows us to heavily optimize the
// main part. But anyway, most current (August 2014) browsers can't handle
// strings 1 << 28 chars or longer, so:
if (str.length * count >= 1 << 28) {
throw new RangeError('repeat count must not overflow maximum string size');
}
var rpt = '';
for (;;) {
if ((count & 1) == 1) {
rpt += str;
}
count >>>= 1;
if (count == 0) {
break;
}
str += str;
}
// Could we try:
// return Array(count + 1).join(this);
return rpt;
}
}
Run Code Online (Sandbox Code Playgroud)
bon*_*bon 12
另一种选择是:
for(var word = ''; word.length < 10; word += 'a'){}
Run Code Online (Sandbox Code Playgroud)
如果你需要重复多个字符,请乘以条件:
for(var word = ''; word.length < 10 * 3; word += 'foo'){}
Run Code Online (Sandbox Code Playgroud)
注意:您不必像1一样超调1word = Array(11).join('a')
小智 10
如果您不反对在项目中包含库,则lodash具有重复功能.
_.repeat('*', 3);
// ? '***
Run Code Online (Sandbox Code Playgroud)
https://lodash.com/docs#repeat
Joh*_*ers 10
以下函数的执行速度比接受的答案中建议的选项快得多:
var repeat = function(str, count) {
var array = [];
for(var i = 0; i < count;)
array[i++] = str;
return array.join('');
}
Run Code Online (Sandbox Code Playgroud)
你会这样使用它:
var repeatedString = repeat("a", 10);
Run Code Online (Sandbox Code Playgroud)
要比较此函数的性能与接受的答案中提出的选项的性能,请参阅此小提琴和此小提琴的基准.
在现代浏览器中,您现在可以使用String.prototype.repeat方法执行此操作:
var repeatedString = "a".repeat(10);
Run Code Online (Sandbox Code Playgroud)
在MDN上阅读有关此方法的更多信息.
此选项更快.不幸的是,它在任何版本的Internet Explorer中都不起作用.表中的数字指定了完全支持该方法的第一个浏览器版本:
Array(10).fill('a').join('')
Run Code Online (Sandbox Code Playgroud)
虽然投票最多的答案更紧凑,但通过这种方法,您不必添加额外的数组项.
String.repeat()目前已有96.39%的浏览器支持。
function pad(text, maxLength){
return text + "0".repeat(maxLength - text.length);
}
console.log(pad('text', 7)); //text000
Run Code Online (Sandbox Code Playgroud)
/**
* Repeat a string `n`-times (recursive)
* @param {String} s - The string you want to repeat.
* @param {Number} n - The times to repeat the string.
* @param {String} d - A delimiter between each string.
*/
var repeat = function (s, n, d) {
return --n ? s + (d || "") + repeat(s, n, d) : "" + s;
};
var foo = "foo";
console.log(
"%s\n%s\n%s\n%s",
repeat(foo), // "foo"
repeat(foo, 2), // "foofoo"
repeat(foo, "2"), // "foofoo"
repeat(foo, 2, "-") // "foo-foo"
);
Run Code Online (Sandbox Code Playgroud)
在ES2015/ES6中,您可以使用 "*".repeat(n)
所以只需将它添加到您的项目中,您就可以了.
String.prototype.repeat = String.prototype.repeat ||
function(n) {
if (n < 0) throw new RangeError("invalid count value");
if (n == 0) return "";
return new Array(n + 1).join(this.toString())
};
Run Code Online (Sandbox Code Playgroud)
另一种快速重复n个字符的有趣方法是使用快速取幂算法的思路:
var repeatString = function(string, n) {
var result = '', i;
for (i = 1; i <= n; i *= 2) {
if ((n & i) === i) {
result += string;
}
string = string + string;
}
return result;
};
Run Code Online (Sandbox Code Playgroud)
只是为了好玩,这是使用toFixed() 的另一种方法,用于格式化浮点数。
通过做
(0).toFixed(2)
(0).toFixed(3)
(0).toFixed(4)
Run Code Online (Sandbox Code Playgroud)
我们得到
0.00
0.000
0.0000
Run Code Online (Sandbox Code Playgroud)
0.如果删除前两个字符,我们可以使用此重复模式来生成任何重复。
(0).toFixed(2)
(0).toFixed(3)
(0).toFixed(4)
Run Code Online (Sandbox Code Playgroud)