在 JavaScript 中重复某个字符串多次

发布于 2024-08-14 07:28:35 字数 200 浏览 4 评论 0原文

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

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

Is there a simple way to finish this in Javascript?显然我可以使用一个函数,但我想知道是否有任何内置方法或其他一些巧妙的技术。

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

$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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(24

凡间太子 2024-08-21 07:28:35

如今,重复 字符串方法几乎在任何地方都实现了。 (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 循环附加来多次重复一个字符(尽管有点不太简洁),速度更快。

These days, the repeat string method is implemented almost everywhere. (It is not in Internet Explorer.) So unless you need to support older browsers, you can simply write:

"a".repeat(10)

Before repeat, we used this 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.join puts the argument between the array elements.)

Simon also points out that according to this benchmark, 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).

听不够的曲调 2024-08-21 07:28:35

在新的 ES6 和谐中,您将可以使用 repeat 来执行此操作。另外,ES6 目前还只是实验性的,此功能已经可用 Edge、FF、Chrome 和 Safari

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

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

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 available in Edge, FF, Chrome and Safari

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

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

昔日梦未散 2024-08-21 07:28:35

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

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

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

淤浪 2024-08-21 07:28:35
Array(10).fill('a').join('')

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

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.

花开浅夏 2024-08-21 07:28:35

另一种方法是:

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

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

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

注意:您不必像 word = Array(11).join('a' 那样超出 1 )

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

緦唸λ蓇 2024-08-21 07:28:35

最提高性能的方法是 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;
  }
}

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

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;
  }
}
秉烛思 2024-08-21 07:28:35

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

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

https://lodash.com/docs#repeat

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

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

https://lodash.com/docs#repeat

野生奥特曼 2024-08-21 07:28:35

对于所有浏览器

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

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

您可以像这样使用它:

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

要将此函数的性能与接受的答案中建议的选项的性能进行比较,请参阅这个小提琴这个 Fiddle 用于基准测试。

仅适用于现代浏览器

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

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

MDN

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

在此处输入图像描述

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 Fiddle and this Fiddle for benchmarks.

For moderns browsers only

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

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

Read more about this method on 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:

enter image description here

固执像三岁 2024-08-21 07:28:35

目前 96.39% 的浏览器支持 String.repeat()

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

String.repeat() is supported by 96.39% of browsers as of now.

function pad(text, maxLength){ 
  return text + "0".repeat(maxLength - text.length);
}
console.log(pad('text', 7)); //text000
东风软 2024-08-21 07:28:35

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

In ES2015/ES6 you can use "*".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()) 
    };
扭转时空 2024-08-21 07:28:35
/**  
 * 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"
);
/**  
 * 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"
);
穿透光 2024-08-21 07:28:35

只是为了好玩,这是使用 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));

Just for the fun of it, here is another way by using the toFixed(), used to format floating point numbers.

By doing

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

we get

0.00
0.000
0.0000

If the first two characters 0. are deleted, we can use this repeating pattern to generate any repetition.

function repeat(str, nTimes) {
  return (0).toFixed(nTimes).substr(2).replaceAll('0', str);
}

console.info(repeat('3', 5));
console.info(repeat('hello ', 4));

夜光 2024-08-21 07:28:35

另一种快速重复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;
};

Another interesting way to quickly repeat n character is to use idea from quick exponentiation algorithm:

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;
};
茶底世界 2024-08-21 07:28:35

为了在我的项目中重复一个值,我使用重复

例如:

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

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

For repeat a value in my projects i use repeat

For example:

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

but be careful because this method has been added to the ECMAScript 6 specification.

千紇 2024-08-21 07:28:35
function repeatString(n, string) {
var repeat = [];
repeat.length = n + 1;
return repeat.join(string);
}

repeatString(3,'x'); // => xxx
repeatString(10,'

function repeatString(n, string) {
  var repeat = [];
  repeat.length = n + 1;
  return repeat.join(string);
}

repeatString(3,'x'); // => xxx
repeatString(10,'????'); // => "????????????????????????????????????????"
神回复 2024-08-21 07:28:35

这是您如何调用函数并借助 Array() 和 join()

使用 Typescript 和 arrow fun

const repeatString = (str: string, num: number) => num > 0 ?
Array(num+1).join(str) : "";

console.log(repeatString("

This is how you can call a function and get the result by the helps of Array() and join()

using Typescript and arrow fun

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: ????????????????????????????????????????

横笛休吹塞上声 2024-08-21 07:28:35

这是我使用的:

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

Here is what I use:

function repeat(str, num) {
        var holder = [];
        for(var i=0; i<num; i++) {
            holder.push(str);
        }
        return holder.join('');
    }
霞映澄塘 2024-08-21 07:28:35

我意识到这不是一个受欢迎的任务,如果您需要重复字符串不是整数次数怎么办?

可以使用 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))

I realize that it's not a popular task, what if you need to repeat your string not an integer number of times?

It's possible with repeat() and slice(), here's how:

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

And below a shortened version:

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

却一份温柔 2024-08-21 07:28:35

我将详细阐述 @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>

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

I'm going to expand on @bonbon's answer. His method is an easy way to "append N chars to an existing string", just in case anyone needs to do that. For example since "a google" is a 1 followed by 100 zeros.

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>

NOTE: You do have to add the length of the original string to the conditional.

感情废物 2024-08-21 07:28:35

Lodash 提供与 Javascript Repeat() 函数并非在所有浏览器中都可用。它称为 _.repeat,自版本 3.0.0 起可用:

_.repeat('a', 10);

Lodash offers a similar functionality as the Javascript repeat() function which is not available in all browers. It is called _.repeat and available since version 3.0.0:

_.repeat('a', 10);
若无相欠,怎会相见 2024-08-21 07:28:35
var stringRepeat = function(string, val) {
  var newString = [];
    for(var i = 0; i < val; i++) {
      newString.push(string);
  }
  return newString.join('');
}

var repeatedString = stringRepeat("a", 1);
var stringRepeat = function(string, val) {
  var newString = [];
    for(var i = 0; i < val; i++) {
      newString.push(string);
  }
  return newString.join('');
}

var repeatedString = stringRepeat("a", 1);
月棠 2024-08-21 07:28:35

也可以用作单行:

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

Can be used as a one-liner too:

function repeat(str, len) {
    while (str.length < len) str += str.substr(0, len-str.length);
    return str;
}
很快妥协 2024-08-21 07:28:35

在咖啡脚本中:

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

In CoffeeScript:

( 'a' for dot in [0..10]).join('')
对岸观火 2024-08-21 07:28:35
String.prototype.repeat = function (n) { n = Math.abs(n) || 1; return Array(n + 1).join(this || ''); };

// console.log("0".repeat(3) , "0".repeat(-3))
// return: "000" "000"
String.prototype.repeat = function (n) { n = Math.abs(n) || 1; return Array(n + 1).join(this || ''); };

// console.log("0".repeat(3) , "0".repeat(-3))
// return: "000" "000"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文