Repeat Character N Times
In Perl I can repeat a character multiple times using the syntax:
$a = "a" x 10; // results in "aaaaaaaaaa"
Is there a simple way to accomplish this in Javascript? I can obviously use a function, but I was wondering if there was any built in approach, or some other clever technique.
These days, the repeat
string method is implemented almost everywhere. So the best way to do this is:
"a".repeat(10)
Before repeat
, we had to use this hack:
Array(11).join("a") // create string with 10 a's: "aaaaaaaaaa"
(Note that an array of length 11 gets you only 10 "a"s, since Array.join
puts the argument between the array elements.)
Simon also points out that according to this jsperf, it appears that it's faster in Safari and Chrome (but not Firefox) to repeat a character multiple times by simply appending using a for loop (although a bit less concise).
In a new ES6 harmony, you will have native way for doing this with repeat. Also ES6 right now only experimental, this feature is already available in Edge, FF, Chrome and Safari
"abc".repeat(3) // "abcabcabc"
And surely if repeat function is not available you can use old-good Array(n + 1).join("abc")
方便,如果你重复自己很多:
String.prototype.repeat= function(n){
n= n || 1;
return Array(n+1).join(this);
}
alert('Are we there yet?nNo.n'.repeat(10))
链接地址: http://www.djcxy.com/p/68580.html
上一篇: 用两位小数解析浮点数
下一篇: 重复N次