Javascript 重复字符 N 次

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1877475/
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-22 21:43:03  来源:igfitidea点击:

Repeat Character N Times

javascriptstringcharacterrepeat

提问by Steve

In Perl I can repeat a character multiple times using the syntax:

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

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

Is there a simple way to accomplish this in Javascript? I can obviously use a function, but I was wondering if there was any built in approach, or some other clever technique.

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

回答by Jason Orendorff

These days, the repeatstring methodis implemented almosteverywhere. (It is not in Internet Explorer.) So unless you need to support older browsers, you can simply write:

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

"a".repeat(10)

Before repeat, we used this hack:

之前repeat,我们使用了这个 hack:

Array(11).join("a") // create string with 10 a's: "aaaaaaaaaa"

(Note that an array of length 11 gets you only 10 "a"s, since Array.joinputs the argument betweenthe array elements.)

(请注意,长度为 11 的数组只能得到 10 个“a”,因为Array.join将参数放在数组元素之间。)

Simon also points out that according to this jsperf, it appears that it's faster in Safari and Chrome (but not Firefox) to repeat a character multiple times by simply appending using a for loop (although a bit less concise).

Simon 还指出,根据这个 jsperf,在 Safari 和 Chrome(但不是 Firefox)中,通过简单地使用 for 循环附加多次重复一个字符似乎更快(虽然有点不那么简洁)。

回答by Salvador Dali

In a new ES6 harmony, you will have native way for doing this with repeat. Also ES6 right now only experimental, this feature is already availablein Edge, FF, Chrome and Safari

在新的 ES6 和声中,您将有使用repeat执行此操作的原生方式。ES6 目前还只是实验性的,这个功能已经在 Edge、FF、Chrome 和 Safari 中可用

"abc".repeat(3) // "abcabcabc"

And surely if repeat function is not available you can use old-good Array(n + 1).join("abc")

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

回答by kennebec

Convenient if you repeat yourself a lot:

如果你经常重复自己的话很方便:

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

回答by Konstantin Victorov

The most performance-wice way is 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/repeat

Short version is below.

简短版本如下。

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

Polyfill from Mozilla:

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

回答by bonbon

An alternative is:

另一种选择是:

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

If you need to repeat multiple chars, multiply your conditional:

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

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

NOTE:You do not have to overshoot by 1 as with word = Array(11).join('a')

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

回答by Nathan Danger

If you're not opposed to including a library in your project, lodash has a repeat function.

如果你不反对在你的项目中包含一个库,lodash 有一个重复功能。

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

https://lodash.com/docs#repeat

https://lodash.com/docs#repeat

回答by John Slegers

For all browsers

适用于所有浏览器

The following function will perform a lot faster than the option suggested in the accepted answer:

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

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

You'd use it like this :

你会像这样使用它:

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

To compare the performance of this function with that of the option proposed in the accepted answer, see this Fiddleand this Fiddlefor benchmarks.

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

For moderns browsers only

仅适用于现代浏览器

In modern browsers, you can now do this using String.prototype.repeatmethod:

在现代浏览器中,您现在可以使用String.prototype.repeat方法执行此操作:

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

Read more about this method on MDN.

MDN上阅读有关此方法的更多信息。

This option is even faster. Unfortunately, it doesn't work in any version of Internet explorer. The numbers in the table specify the first browser version that fully supports the method:

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

enter image description here

在此处输入图片说明

回答by Grzegorz Pawlik

Array(10).fill('a').join('')

Although the most voted answer is a bit more compact, with this approach you don't have to add an extra array item.

尽管投票最多的答案更紧凑一些,但使用这种方法您不必添加额外的数组项。

回答by webdeb

In ES2015/ES6 you can use "*".repeat(n)

在 ES2015/ES6 中你可以使用 "*".repeat(n)

So just add this to your projects, and your are good to go.

所以只需将它添加到您的项目中,您就可以开始了。

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

回答by yckart

/**  
 * 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"
);