在Perl中,我可以使用以下语法多次重复一个字符:
$a = "a" x 10; // results in "aaaaaaaaaa"
有没有一种简单的方法在Javascript中实现这一点?我显然可以使用一个函数,但我想知道是否有内置的方法,或者其他一些巧妙的技术。
在Perl中,我可以使用以下语法多次重复一个字符:
$a = "a" x 10; // results in "aaaaaaaaaa"
有没有一种简单的方法在Javascript中实现这一点?我显然可以使用一个函数,但我想知道是否有内置的方法,或者其他一些巧妙的技术。
当前回答
我将详细介绍@bonbon的答案。他的方法是一种“将N个字符附加到现有字符串”的简单方法,以防任何人需要这样做。例如,因为“a google”是1后跟100个零。
对于(var google='1';google.length<1+100;google+='0'){}document.getElementById('el').innerText=google;<div>这是“谷歌”:</div><div id=“el”></div>
注意:您必须将原始字符串的长度添加到条件中。
其他回答
在一个新的ES6和声中,你将有自己的方法来重复。此外,ES6目前只是实验性的,该功能已在Edge、FF、Chrome和Safari中提供
"abc".repeat(3) // "abcabcabc"
当然,如果重复功能不可用,您可以使用旧的好数组(n+1).join(“abc”)
另一种快速重复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;
};
如今,重复字符串方法几乎在所有地方都得到了实现。(它不在Internet Explorer中。)因此,除非您需要支持较旧的浏览器,否则只需编写:
"a".repeat(10)
在重复之前,我们使用了这个黑客:
Array(11).join("a") // create string with 10 a's: "aaaaaaaaaa"
(注意,长度为11的数组只能得到10个“a”,因为array.join将参数放在数组元素之间。)
西蒙还指出,根据这个基准,在Safari和Chrome(而不是Firefox)中,通过简单地使用for循环追加一个字符来重复多次似乎更快(虽然有点不那么简洁)。
最有效的方法是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;
}
}
如果你经常重复自己的话,那么很方便:
String.prototype.repeat=String.prototype.repeat||函数(n){n=n||1;return Array(n+1).join(this);}alert('我们到了吗?\n没有。\n'。重复(10))