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

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

有没有一种简单的方法在Javascript中实现这一点?我显然可以使用一个函数,但我想知道是否有内置的方法,或者其他一些巧妙的技术。


当前回答

如果您不反对在项目中包含库,lodash有一个repeat函数。

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

https://lodash.com/docs#repeat

其他回答

截至目前,96.39%的浏览器支持String.repeat()。

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

对于重复项目中的值,我使用repeat

例如:

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

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

我意识到这不是一个流行的任务,如果你需要重复字符串而不是整数次呢?

使用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=函数(n){如果(n<0)n=0;返回this.repeat(n)+this.slice(0,~~((n-~n)*this.length));}var s=“abcd”;console.log(s.fracRepeat(2.5))

为了好玩,这里有另一种方法,使用toFixed()来格式化浮点数。

通过做

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

我们得到

0.00
0.000
0.0000

如果前两个字符为0。我们可以使用这个重复模式来生成任何重复。

函数重复(str,nTimes){return(0).toFixed(n次).substr(2).replaceAll(“0”,str);}console.info(重复('3',5));console.info(重复('hello',4));

在ES2015/ES6中,您可以使用“*”。重复(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()) 
    };