在Perl中,我可以使用以下语法多次重复一个字符:
$a = "a" x 10; // results in "aaaaaaaaaa"
有没有一种简单的方法在Javascript中实现这一点?我显然可以使用一个函数,但我想知道是否有内置的方法,或者其他一些巧妙的技术。
在Perl中,我可以使用以下语法多次重复一个字符:
$a = "a" x 10; // results in "aaaaaaaaaa"
有没有一种简单的方法在Javascript中实现这一点?我显然可以使用一个函数,但我想知道是否有内置的方法,或者其他一些巧妙的技术。
当前回答
另一种选择是:
for(var word = ''; word.length < 10; word += 'a'){}
如果需要重复多个字符,请乘以条件:
for(var word = ''; word.length < 10 * 3; word += 'foo'){}
注意:您不必像word=Array(11)那样超出1。join('a')
其他回答
最有效的方法是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;
}
}
在一个新的ES6和声中,你将有自己的方法来重复。此外,ES6目前只是实验性的,该功能已在Edge、FF、Chrome和Safari中提供
"abc".repeat(3) // "abcabcabc"
当然,如果重复功能不可用,您可以使用旧的好数组(n+1).join(“abc”)
如果你经常重复自己的话,那么很方便:
String.prototype.repeat=String.prototype.repeat||函数(n){n=n||1;return Array(n+1).join(this);}alert('我们到了吗?\n没有。\n'。重复(10))
Lodash提供了与Javascript repeat()函数类似的功能,这在所有浏览器中都不可用。它名为_.repeat,从3.0.0版开始提供:
_.repeat('a', 10);
对于重复项目中的值,我使用repeat
例如:
var n = 6;
for (i = 0; i < n; i++) {
console.log("#".repeat(i+1))
}
但要小心,因为该方法已添加到ECMAScript 6规范中。