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

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

是有一个简单的方式完成这Javascript?我显然可以使用一个功能,但我想知道如果有任何内在的方法,或一些其他的巧妙的技术。

其他提示

在新的ES6和谐,你将有与的重复。此外ES6现在只是试验性的,这个功能是已经可以在边缘,FF,铬和Safari

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

和肯定,如果重复功能不可用,你可以使用旧的好Array(n + 1).join("abc")

方便,如果你重复自己很多:

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

最性能WICE方式是 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的:

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

另一种方法是:

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

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

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

注意:您不必由1与word = Array(11).join('a')过头

如果你不反对,包括在你的项目库,lodash具有复读功能。

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

https://lodash.com/docs#repeat

对于所有浏览器

下面的函数将更快地执行很多比建议的选项中接受的答案:

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

您会使用这样的:

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

要与在接受的答案提出的选项进行比较这一功能的性能,请参见 此小提琴 此小提琴 以基准。

对于现代人浏览器只

在现代浏览器中,你现在可以做到这一点使用方法String.prototype.repeat

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

了解更多关于 MDN

这个选项甚至更快。不幸的是,它并没有在Internet Explorer的任何版本。在表中的数字指定所述第一浏览器版本,完全支持方法:

“在这里输入的图像描述”

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

虽然大多数投票的答案是更紧凑一点,用这种方法,你不必添加额外的数组项。

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

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

另一种有趣的方式来的快速的重复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;
};

有关重复在我的项目一个值i重复使用

例如:

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

但是,因为此方法已被添加到所述的ECMAScript 6规范要小心。

下面是我用:

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

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

我要在 @邦邦的回答扩大。他的方法是“N字符添加到现有的字符串”,以防万一有人需要做一个简单的方法。例如由于“一个谷歌”是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>

注意:您确实有原始字符串的长度增加了条件

Lodash 提供了一个类似的功能 Javascript重复() 功能不是提供在所有浏览器.它被称为 _.重复 并且由于可用的版本为3.0.0:

_.repeat('a', 10);
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);

可作为一个班轮太:

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

在CoffeeScript的:

( 'a' for dot in [0..10]).join('')
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"

下面是一种ES6版本

const repeat = (a,n) => Array(n).join(a+"|$|").split("|$|");
repeat("A",20).forEach((a,b) => console.log(a,b+1))

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top