在 Perl 中,我可以使用以下语法多次重复一个字符:
$a = "a" x 10; // results in "aaaaaaaaaa"
有没有一种简单的方法可以在 Javascript 中实现这一点?我显然可以使用一个函数,但我想知道是否有任何内置方法或其他一些聪明的技术。
如今,repeat
string method几乎在所有地方都实现了。 (它是 not in Internet Explorer。)因此,除非您需要支持较旧的浏览器,否则您可以简单地编写:
"a".repeat(10)
在 repeat
之前,我们使用了这个 hack:
Array(11).join("a") // create string with 10 a's: "aaaaaaaaaa"
(请注意,长度为 11 的数组只能得到 10 个“a”,因为 Array.join
将参数放在 数组元素之间。)
Simon 还指出,根据 this benchmark,在 Safari 和 Chrome(但不是 Firefox)中,通过简单地使用 for 循环进行附加来多次重复一个字符似乎更快(虽然不太简洁)。
在新的 ES6 和谐中,您将拥有使用 repeat 执行此操作的本地方式。 ES6 现在也只是实验性的,这个功能是 already available 在 Edge、FF、Chrome 和 Safari
"abc".repeat(3) // "abcabcabc"
当然,如果重复功能不可用,您可以使用 old-good Array(n + 1).join("abc")
如果你经常重复自己的话会很方便:
String.prototype.repeat = String.prototype.repeat ||函数(n){ n= n || 1个;返回 Array(n+1).join(this); } alert( '我们到了吗?\nNo.\n'.repeat(10) )
repeat(str, n)
。
n= n || 1
部分(或检查 n
是否未定义),因此您也可以重复 0
次。
String.repeat
仅在 ES6 中添加,直到 2015 年 6 月才最终确定。所以我认为我的观点在我 2012 年编写时是有效的。:)
Array(10).fill('a').join('')
尽管投票最多的答案更紧凑,但使用这种方法,您不必添加额外的数组项。
join("a")
,为什么还要使用额外的方法 fill()
...
另一种选择是:
for(var word = ''; word.length < 10; word += 'a'){}
如果您需要重复多个字符,请乘以您的条件:
for(var word = ''; word.length < 10 * 3; word += 'foo'){}
注意:您不必像 word = Array(11).join('a')
那样超调 1
性能最佳的方式是 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;
}
}
count >>>= 1, pattern += pattern;
的含义吗?什么样的声明?
if (!String.prototype.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);
要将此函数的性能与已接受答案中提出的选项的性能进行比较,请参阅 this Fiddle 和 this Fiddle 以了解基准。
仅适用于现代浏览器
在现代浏览器中,您现在可以使用 String.prototype.repeat
方法执行此操作:
var repeatedString = "a".repeat(10);
在 MDN 上阅读有关此方法的更多信息。
这个选项甚至更快。不幸的是,它不适用于任何版本的 Internet Explorer。表中的数字指定了完全支持该方法的第一个浏览器版本:
https://i.stack.imgur.com/B3PVU.png
在 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())
};
/**
* 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"
);
另一种快速重复 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;
};
只是为了好玩,这里是另一种使用 toFixed() 的方式,用于格式化浮点数。
通过做
(0).toFixed(2)
(0).toFixed(3)
(0).toFixed(4)
我们得到
0.00
0.000
0.0000
如果前两个字符 0.
被删除,我们可以使用这种重复模式来生成任何重复。
function repeat(str, nTimes) { return (0).toFixed(nTimes).substr(2).replaceAll('0', str); } 控制台信息(重复('3',5));控制台信息(重复('你好',4));
为了在我的项目中重复一个值,我使用重复
例如:
var n = 6;
for (i = 0; i < n; i++) {
console.log("#".repeat(i+1))
}
但要小心,因为此方法已添加到 ECMAScript 6 规范中。
function repeatString(n, string) {
var repeat = [];
repeat.length = n + 1;
return repeat.join(string);
}
repeatString(3,'x'); // => xxx
repeatString(10,'🌹'); // => "🌹🌹🌹🌹🌹🌹🌹🌹🌹🌹"
这是我使用的:
function repeat(str, num) {
var holder = [];
for(var i=0; i<num; i++) {
holder.push(str);
}
return holder.join('');
}
右填充零,没有数组或循环。只需使用 ES6 2015 使用 repeat()
,它现在有 wide support。如果切换串联,则左焊盘。
function pad(text, maxLength){
var res = text + "0".repeat(maxLength - text.length);
return res;
}
console.log(pad('hello', 8)); //hello000
我将在 @bonbon's answer 上进行扩展。他的方法是“将 N 个字符附加到现有字符串”的简单方法,以防万一有人需要这样做。例如,从 "a google" is a 1 followed by 100 zeros 开始。
for(var google = '1'; google.length < 1 + 100; google += '0'){} document.getElementById('el').innerText = google;
注意:您必须将原始字符串的长度添加到条件中。
Lodash 提供与 Javascript repeat() 功能类似的功能,但并非在所有浏览器中都可用。它被称为 _.repeat 并且从版本 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('')
这就是您可以通过 Array() 和 join() 调用函数并获取结果的方式
function repeatStringNumTimes(str, num) { // 在我之后重复 return num > 0 ? Array(num+1).join(str) : ""; } console.log(repeatStringNumTimes("a",10))
我意识到这不是一项受欢迎的任务,如果您需要重复您的字符串而不是整数次怎么办?
String.prototype.fracRepeat = function(n){
if(n < 0) n = 0;
var n_int = ~~n; // amount of whole times to repeat
var n_frac = n - n_int; // amount of fraction times (e.g., 0.5)
var frac_length = ~~(n_frac * this.length); // length in characters of fraction part, floored
return this.repeat(n) + this.slice(0, frac_length);
}
下面是一个缩短的版本:
String.prototype.fracRepeat = function(n){ if(n < 0) n = 0;返回 this.repeat(n) + this.slice(0, ~~((n - ~~n) * this.length)); } var s = "abcd"; console.log(s.fracRepeat(2.5))
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"
String.prototype.repeat
。另外,为什么要缩小它?您无需将所有内容写在一行中。
这是一个 ES6 版本
常量重复 = (a,n) => Array(n).join(a+"|$|").split("|$|");重复("A",20).forEach((a,b) => console.log(a,b+1))
不定期副业成功案例分享
Array(rawValue.length + 1).join("*")
Array(n+1).join("a")
。当 n=0 时,返回空字符串,当 n=1 时,返回"a"
。所以我认为它适用于所有情况。