This question already has an answer here:
这个问题在这里已有答案:
- Repeat Character N Times 21 answers
重复字符N次21个答案
I'd like to insert a letter equal to the number returned by a calculation within my code :
我想在我的代码中插入一个等于计算返回的数字的字母:
var howmanytimes = 500 / 100;
$('#mytextmultiplied').text(howmanytimes*'whatiwanttowrite');
The last part is obviously wrong. Is looping the only option here?
最后一部分显然是错误的。循环是这里唯一的选择吗?
2 个解决方案
#1
Here's a technique:
这是一种技巧:
var howmanytimes = 500 / 100;
var repeatedText = (howmanytimes < 1) ? '' : new Array(howmanytimes + 1).join(whatiwanttowrite);
$('#mytextmultiplied').text(repeatedText);
The above technique is not the fastest. For more efficient (but longer code-wise) techniques, see the answers in these similar questions:
上述技术并不是最快的。要获得更高效(但代码更长)的技术,请参阅以下类似问题中的答案:
- Repeat Character N Times
- How to create a string with n characters? How to create a string with specific length?
- Create a string of variable length, filled with a repeated character
- Repeat String - Javascript
重复字符N次
如何创建一个包含n个字符的字符串?如何创建具有特定长度的字符串?
创建一个可变长度的字符串,填充重复的字符
重复字符串 - Javascript
Someday you will be able to use String.prototype.repeat
总有一天你可以使用String.prototype.repeat
#2
You need a for
loop like this: fiddle
你需要这样的for循环:小提琴
var howmanytimes = 500 / 100;
//create a loop - i variable increments on each loop until it reaches 'howmanytimes'
for(var i = 0; i <= howmanytimes ; i++) {
//here is your code to run on each loop -
$('#mytextmultiplied').append('whatiwanttowrite' + "<br />");
}
#1
Here's a technique:
这是一种技巧:
var howmanytimes = 500 / 100;
var repeatedText = (howmanytimes < 1) ? '' : new Array(howmanytimes + 1).join(whatiwanttowrite);
$('#mytextmultiplied').text(repeatedText);
The above technique is not the fastest. For more efficient (but longer code-wise) techniques, see the answers in these similar questions:
上述技术并不是最快的。要获得更高效(但代码更长)的技术,请参阅以下类似问题中的答案:
- Repeat Character N Times
- How to create a string with n characters? How to create a string with specific length?
- Create a string of variable length, filled with a repeated character
- Repeat String - Javascript
重复字符N次
如何创建一个包含n个字符的字符串?如何创建具有特定长度的字符串?
创建一个可变长度的字符串,填充重复的字符
重复字符串 - Javascript
Someday you will be able to use String.prototype.repeat
总有一天你可以使用String.prototype.repeat
#2
You need a for
loop like this: fiddle
你需要这样的for循环:小提琴
var howmanytimes = 500 / 100;
//create a loop - i variable increments on each loop until it reaches 'howmanytimes'
for(var i = 0; i <= howmanytimes ; i++) {
//here is your code to run on each loop -
$('#mytextmultiplied').append('whatiwanttowrite' + "<br />");
}