如何将一个字符串重复n次? (JavaScript)

问题描述 投票:0回答:24

在 Perl 中,我可以使用语法多次重复一个字符:

$a = "a" x 10; // results in "aaaaaaaaaa"

有没有一种简单的方法可以在 Javascript 中完成此任务?我显然可以使用一个函数,但我想知道是否有任何内置方法,或其他一些聪明的技术。

javascript string character repeat
24个回答
1665
投票

如今,

repeat
字符串方法几乎到处都实现了。 (它不在 Internet Explorer 中。)因此,除非您需要支持较旧的浏览器,否则您可以简单地编写:

"a".repeat(10)

repeat

之前,我们使用了这个技巧:

Array(11).join("a") // create string with 10 a's: "aaaaaaaaaa"
(请注意,长度为 11 的数组只能得到 10 个“a”,因为 

Array.join

 将参数 
放在 数组元素之间。)

Simon 还指出,根据

此基准测试,在 Safari 和 Chrome(但不是 Firefox)中,通过简单地使用 for 循环附加来重复一个字符多次(尽管有点不太简洁)似乎更快。


324
投票
在新的 ES6 Harmony 中,您将拥有通过

repeat 执行此操作的原生方法。另外,ES6 目前还只是实验性的,此功能已经在 Edge、FF、Chrome 和 Safari 中可用 "abc".repeat(3) // "abcabcabc"

当然,如果重复功能不可用,您可以使用旧的好
Array(n + 1).join("abc")

    


57
投票

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) )


19
投票
虽然投票最多的答案有点紧凑,但使用这种方法您不必添加额外的数组项。


15
投票

for(var word = ''; word.length < 10; word += 'a'){}

如果您需要重复多个字符,请将条件相乘:

for(var word = ''; word.length < 10 * 3; word += 'foo'){}

注意:

您不必像 word = Array(11).join('a')

 那样超调 1
    


12
投票
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));

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; } }



11
投票

_.repeat('*', 3); // → '***

https://lodash.com/docs#repeat


10
投票

以下功能的执行速度比已接受答案中建议的选项快得多:

var repeat = function(str, count) { var array = []; for(var i = 0; i < count;) array[i++] = str; return array.join(''); }

你会像这样使用它:

var repeatedString = repeat("a", 10);

要将此功能的性能与已接受答案中提出的选项的性能进行比较,请参阅 

this Fiddlethis Fiddle 了解基准。 仅适用于现代浏览器

在现代浏览器中,您现在可以使用

String.prototype.repeat

方法来执行此操作:


var repeatedString = "a".repeat(10);

MDN

上了解有关此方法的更多信息。 此选项甚至更快。不幸的是,它不适用于任何版本的 Internet Explorer。表中的数字指定完全支持该方法的第一个浏览器版本:

enter image description here


8
投票
String.repeat()

目前已被 96.39% 的浏览器支持。

function pad(text, maxLength){ 
  return text + "0".repeat(maxLength - text.length);
}
console.log(pad('text', 7)); //text000



7
投票
"*".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()) };



5
投票


5
投票
toFixed()

,用于格式化浮点数。 通过做

(0).toFixed(2) (0).toFixed(3) (0).toFixed(4)

我们得到

0.00 0.000 0.0000

如果删除了前两个字符
0.

,我们可以使用此重复模式来生成任何重复。

function repeat(str, nTimes) { return (0).toFixed(nTimes).substr(2).replaceAll('0', str); } console.info(repeat('3', 5)); console.info(repeat('hello ', 4));


4
投票
快速

重复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; };



2
投票

例如:

var n = 6; for (i = 0; i < n; i++) { console.log("#".repeat(i+1)) }

但要小心,因为此方法已添加到 ECMAScript 6 规范中。


2
投票


2
投票

使用 Typescript 和箭头乐趣

const repeatString = (str: string, num: number) => num > 0 ? Array(num+1).join(str) : ""; console.log(repeatString("🌷",10)) //outputs: 🌷🌷🌷🌷🌷🌷🌷🌷🌷🌷

function repeatString(str, num) { // Array(num+1) is the string you want to repeat and the times to repeat the string return num > 0 ? Array(num+1).join(str) : ""; } console.log(repeatString("a",10)) // outputs: aaaaaaaaaa console.log(repeatString("🌷",10)) //outputs: 🌷🌷🌷🌷🌷🌷🌷🌷🌷🌷


1
投票

function repeat(str, num) { var holder = []; for(var i=0; i<num; i++) { holder.push(str); } return holder.join(''); }



1
投票

不是整数次数怎么办? 可以使用

repeat()

slice()
,具体方法如下:
String.prototype.fracRepeat = function(n){ if(n < 0) n = 0; var n_int = ~~n; // amount of whole times to repeat var n_frac = n - n_int; // amount of fraction times (e.g., 0.5) var frac_length = ~~(n_frac * this.length); // length in characters of fraction part, floored return this.repeat(n) + this.slice(0, frac_length); }

下面是缩短版本:

String.prototype.fracRepeat = function(n){ if(n < 0) n = 0; return this.repeat(n) + this.slice(0, ~~((n - ~~n) * this.length)); } var s = "abcd"; console.log(s.fracRepeat(2.5))


0
投票
@bonbon的答案

。他的方法是一种“将 N 个字符附加到现有字符串”的简单方法,以防万一有人需要这样做。例如,因为 “a google” 是 1 后跟 100 个零

for(var google = '1'; google.length < 1 + 100; google += '0'){} document.getElementById('el').innerText = google;
<div>This is "a google":</div>
<div id="el"></div>

注意:

您必须将原始字符串的长度添加到条件中。


0
投票
Lodash

提供与 Javascript Repeat() 函数类似的功能,但并非在所有浏览器中都可用。它被称为 _.repeat 并且从版本 3.0.0 开始可用: _.repeat('a', 10);



0
投票


0
投票

function repeat(str, len) { while (str.length < len) str += str.substr(0, len-str.length); return str; }



0
投票

( 'a' for dot in [0..10]).join('')



-1
投票
	
© www.soinside.com 2019 - 2024. All rights reserved.