在Perl中,我可以使用语法重复多次一个字符:
在Perl中,我可以使用以下语法重复多次一个字符:
$a = "a" x 10; // results in "aaaaaaaaaa"
有没有在Javascript中实现这个的简单方法?我当然可以使用函数,但我想知道是否有任何内置的方法或其他巧妙的技术。
在Perl中,我可以使用以下语法重复多次一个字符:
$a = "a" x 10; // results in "aaaaaaaaaa"
有没有在Javascript中实现这个的简单方法?我当然可以使用函数,但我想知道是否有任何内置的方法或其他巧妙的技术。
现在几乎所有地方都已经实现了repeat
字符串方法。(它在Internet Explorer中不可用。)所以,除非你需要支持旧版浏览器,你可以简单地编写:
"a".repeat(10)
repeat
之前,我们使用了这个技巧:
Array(11).join("a") // create string with 10 a's: "aaaaaaaaaa"
Array.join
puts the argument between the array elements.)如果你经常需要重复自己,那么很方便:
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) )
n = n || 1
部分(或者检查 n
是否未定义),这样你也可以重复 0
次。 - chodorowiczString.repeat
方法是在 ES6 中加入的,在那之前它并不存在。ES6 是在2015年6月才最终确定的。所以我认为我在2012年写下这句话时是正确的。 :) - tuomassaloArray(10).fill('a').join('')
虽然最被投票的答案更加紧凑,但是采用这种方法你不需要再添加额外的数组项。
join("a")
就能实现相同的功能,为什么还要使用额外的方法fill()
呢? - vsync另一种选择是:
for(var word = ''; word.length < 10; word += 'a'){}
如果你需要重复多个字符,请将条件乘以相应的倍数:
for(var word = ''; word.length < 10 * 3; word += 'foo'){}
注意:与word = Array(11).join('a')
中超出一个的情况不同,您无需超过当前数量。
最高性能的方法是使用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;
的含义吗?这是什么类型的语句? - Tsahi Asherif (!String.prototype.repeat) {
,并在结尾处添加}
即可。 - trlkly下面的函数将比接受答案中提供的选项执行得更快:
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中都不起作用。表格中的数字指定完全支持该方法的第一个浏览器版本:
String.repeat()
目前已被96.39%的浏览器支持。
function pad(text, maxLength){
return text + "0".repeat(maxLength - text.length);
}
console.log(pad('text', 7)); //text000
"*".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())
};
Array(rawValue.length + 1).join("*")
。 - Dexygen