如何在 JavaScript 中重复字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4549894/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:54:51  来源:igfitidea点击:

How can I repeat strings in JavaScript?

javascript

提问by BrokeMyLegBiking

In JavaScript, how would I create a string of repeating strings x number of times:

在 JavaScript 中,我将如何创建重复字符串 x 次的字符串:

var s = new String(" ",3);

//s would now be "   "

回答by Jacob Relkin

There is no such function, but hey, you can create it:

没有这样的功能,但是嘿,你可以创建它:

String.prototype.repeat = function(times) {
   return (new Array(times + 1)).join(this);
};

Usage:

用法:

var s = " ".repeat(3);

Of course you could write this as part of a standalone group of functions:

当然,您可以将其编写为一组独立函数的一部分:

var StringUtilities = {
    repeat: function(str, times) { 
       return (new Array(times + 1)).join(str);
    }
    //other related string functions...
};

Usage:

用法:

var s = StringUtilities.repeat(" ", 3);

回答by Ivo Wetzel

You can also use Array.join:

您还可以使用Array.join

function repeat(str, times) {
    return new Array(times + 1).join(str);
}

> repeat(' ', 3)
"   "

回答by peepsalot

Here's a neat way that involves no loops. In addition to being concise, I'm pretty sure using join is much more efficient for very large strings.

这是一种不涉及循环的巧妙方法。除了简洁之外,我很确定使用 join 对于非常大的字符串更有效。

function repeat(str, num) { 
    return (new Array(num+1)).join(str); 
}

You could also put this code on the String prototype, but I'm of the mindset that it's a bad idea to mess with the prototype of built in types.

您也可以将此代码放在 String 原型上,但我认为混淆内置类型的原型是个坏主意。

回答by Lo?c Faure-Lacroix

I think your best and only way to achieve this is to loop over your string.. As far as I know, there is no such feature in any languages.

我认为你最好也是唯一的方法是循环你的字符串。据我所知,任何语言都没有这样的功能。

function multiString(text, count){
    var ret = "";
    for(var i = 0; i < count; i++){
        ret += text;
    }
    return ret;
}

var myString = multiString("&nbsp;", 3);

But I guess you could figure it out.

但我想你可以弄清楚。

回答by Carlos Valenzuela

Haven't you tried with a loop

你有没有试过循环

for (var i = 0; i < 3; i++) {
     s += "&nbsp;"; }

?

?