题
在Perl我可以重复一字符多次使用的语法:
$a = "a" x 10; // results in "aaaaaaaaaa"
是有一个简单的方式完成这Javascript?我显然可以使用一个功能,但我想知道如果有任何内在的方法,或一些其他的巧妙的技术。
解决方案
这些天, repeat
字符串的方法被实现几乎无处不在。 (这是无法在Internet Explorer 。一>)所以,除非你需要支持旧的浏览器,你可以简单的写:
"a".repeat(10)
repeat
之前,我们使用本hack:
Array(11).join("a") // create string with 10 a's: "aaaaaaaaaa"
(注意,长度为11的数组让你仅10 “一” S,因为Array.join
放参数的 之间的数组元素。)
西蒙还指出,根据此jsperf ,似乎它的速度更快的Safari和铬(但不火狐)通过简单地使用附加多次重复字符的for循环(虽然少一点简明)。
其他提示
方便,如果你重复自己很多:
String.prototype.repeat = String.prototype.repeat || function(n){
n= n || 1;
return Array(n+1).join(this);
}
alert( 'Are we there yet?\nNo.\n'.repeat(10) )
最性能WICE方式是 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的:
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;
}
}
另一种方法是:
for(var word = ''; word.length < 10; word += 'a'){}
如果您需要重复多个字符,乘以你的条件:
for(var word = ''; word.length < 10 * 3; word += 'foo'){}
注意:您不必由1与word = Array(11).join('a')
过头
对于所有浏览器
下面的函数将更快地执行很多比建议的选项中接受的答案:
var repeat = function(str, count) {
var array = [];
for(var i = 0; i < count;)
array[i++] = str;
return array.join('');
}
您会使用这样的:
var repeatedString = repeat("a", 10);
要与在接受的答案提出的选项进行比较这一功能的性能,请参见 此小提琴强> 和的此小提琴强> 以基准。
对于现代人浏览器只
在现代浏览器中,你现在可以做到这一点使用方法String.prototype.repeat
:
var repeatedString = "a".repeat(10);
了解更多关于 MDN 该方法一>
这个选项甚至更快。不幸的是,它并没有在Internet Explorer的任何版本。在表中的数字指定所述第一浏览器版本,完全支持方法:
Array(10).fill('a').join('')
虽然大多数投票的答案是更紧凑一点,用这种方法,你不必添加额外的数组项。
/**
* 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"
);
在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())
};
另一种有趣的方式来的快速的重复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;
};
有关重复在我的项目一个值i重复使用
例如:
var n = 6;
for (i = 0; i < n; i++) {
console.log("#".repeat(i+1))
}
但是,因为此方法已被添加到所述的ECMAScript 6规范要小心。
下面是我用:
function repeat(str, num) {
var holder = [];
for(var i=0; i<num; i++) {
holder.push(str);
}
return holder.join('');
}
function repeatString(n, string) {
var repeat = [];
repeat.length = n + 1;
return repeat.join(string);
}
repeatString(3,'x'); // => xxx
repeatString(10,'🌹'); // => "🌹🌹🌹🌹🌹🌹🌹🌹🌹🌹"
我要在 @邦邦的回答扩大。他的方法是“N字符添加到现有的字符串”,以防万一有人需要做一个简单的方法。例如由于“一个谷歌”是1,接着100个零的
for(var google = '1'; google.length < 1 + 100; google += '0'){}
document.getElementById('el').innerText = google;
<div>This is "a google":</div>
<div id="el"></div>
注意:您确实有原始字符串的长度增加了条件
Lodash 提供了一个类似的功能 Javascript重复() 功能不是提供在所有浏览器.它被称为 _.重复 并且由于可用的版本为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('')
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"
下面是一种ES6版本
const repeat = (a,n) => Array(n).join(a+"|$|").split("|$|");
repeat("A",20).forEach((a,b) => console.log(a,b+1))