在Perl中,我可以使用以下语法多次重复一个字符:
$a = "a" x 10; // results in "aaaaaaaaaa"
有没有一种简单的方法在Javascript中实现这一点?我显然可以使用一个函数,但我想知道是否有内置的方法,或者其他一些巧妙的技术。
在Perl中,我可以使用以下语法多次重复一个字符:
$a = "a" x 10; // results in "aaaaaaaaaa"
有没有一种简单的方法在Javascript中实现这一点?我显然可以使用一个函数,但我想知道是否有内置的方法,或者其他一些巧妙的技术。
当前回答
/**
* 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"
);
其他回答
对于重复项目中的值,我使用repeat
例如:
var n = 6;
for (i = 0; i < n; i++) {
console.log("#".repeat(i+1))
}
但要小心,因为该方法已添加到ECMAScript 6规范中。
为了好玩,这里有另一种方法,使用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));
我将详细介绍@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>
注意:您必须将原始字符串的长度添加到条件中。
另一种快速重复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;
};
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"