返回任意次数的字符串的最佳或最简洁的方法是什么?

以下是我目前为止拍得最好的照片:

function repeat(s, n){
    var a = [];
    while(a.length < n){
        a.push(s);
    }
    return a.join('');
}

当前回答

使用Lodash来实现Javascript的实用功能,比如重复字符串。

Lodash提供了良好的性能和ECMAScript兼容性。

我强烈推荐它用于UI开发,它在服务器端也很好用。

下面是如何使用Lodash重复字符串“yo”2次:

> _.repeat('yo', 2)
"yoyo"

其他回答

我已经测试了所有提议的方法的性能。

这是我找到的最快的变种。

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

或作为独立函数:

function repeat(pattern, count) {
    if (count < 1) return '';
    var result = '';
    while (count > 1) {
        if (count & 1) result += pattern;
        count >>= 1, pattern += pattern;
    }
    return result + pattern;
}

它基于wnrph算法。 它真的很快。与传统的Array(count + 1).join(string)方法相比,计数越大,它的运行速度就越快。

我只改变了两件事:

replace pattern = this with pattern = this. valueof()(清除一个明显的类型转换); 增加if (count < 1)检查从prototypejs到函数的顶部,以排除在这种情况下不必要的操作。 应用优化从丹尼斯的答案(5-7%的速度提高)

UPD

为感兴趣的人准备了一个性能测试场地。

变量计数~ 0 ..100:

常量= 1024:

如果可以的话,使用它,让它更快:)

首先,OP的问题似乎是关于简明性的——我理解的意思是“简单易读”,而大多数答案似乎是关于效率的——这显然不是一回事,而且我认为,除非你实现了一些非常具体的大型数据操作算法,否则当你实现基本的数据操作Javascript函数时,不应该担心。简洁更重要。

其次,正如André Laszlo所指出的,字符串。repeat是ECMAScript 6的一部分,并且已经在几个流行的实现中可用——因此是String最简洁的实现。重复是不执行的;-)

最后,如果您需要支持不提供ECMAScript 6实现的主机,André Laszlo提到的MDN的polyfill一点也不简洁。

所以,废话不多说——下面是我简洁的填充:

String.prototype.repeat = String.prototype.repeat || function(n){
    return n<=1 ? this : this.concat(this.repeat(n-1));
}

是的,这是递归。我喜欢递归——它们很简单,如果操作正确,很容易理解。关于效率,如果语言支持它,如果写得正确,它们可以非常高效。

从我的测试来看,这种方法比Array快60%。加入的方法。虽然它显然与disfate的实现相去甚远,但它比两者都要简单得多。

我的测试设置是节点v0.10,使用“严格模式”(我认为它支持某种TCO),对一个10个字符的字符串调用repeat(1000)一百万次。

ES-Next有很多方法

1. ES2015/ES6已经实现了这个repeat()方法!

/** * str: String * count: Number */ const str = `hello repeat!\n`, count = 3; let resultString = str.repeat(count); console.log(`resultString = \n${resultString}`); /* resultString = hello repeat! hello repeat! hello repeat! */ ({ toString: () => 'abc', repeat: String.prototype.repeat }).repeat(2); // 'abcabc' (repeat() is a generic method) // Examples 'abc'.repeat(0); // '' 'abc'.repeat(1); // 'abc' 'abc'.repeat(2); // 'abcabc' 'abc'.repeat(3.5); // 'abcabcabc' (count will be converted to integer) // 'abc'.repeat(1/0); // RangeError // 'abc'.repeat(-1); // RangeError

2. ES2017/ES8新增String.prototype.padStart()

Const STR = 'abc '; Const times = 3; const newStr = str. padstartlength * times, str.toUpperCase()); console.log(' newStr = ', newStr); // "newStr =" "ABC ABC ABC "

3.ES2017/ES8新增String.prototype.padEnd()

Const STR = 'abc '; Const times = 3; const newStr = str. padend (str。length * times, str.toUpperCase()); console.log(' newStr = ', newStr); // "newStr =" "abc abc abc "

refs

http://www.ecma-international.org/ecma-262/6.0/#sec-string.prototype.repeat

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/padStart

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd

使用Lodash来实现Javascript的实用功能,比如重复字符串。

Lodash提供了良好的性能和ECMAScript兼容性。

我强烈推荐它用于UI开发,它在服务器端也很好用。

下面是如何使用Lodash重复字符串“yo”2次:

> _.repeat('yo', 2)
"yoyo"

只是另一个重复函数:

function repeat(s, n) {
  var str = '';
  for (var i = 0; i < n; i++) {
    str += s;
  }
  return str;
}