2015-05-02 71 views
2

同一文本字符串的好几次我想插入等于我的代码中通过计算返回的数字一个字母:插入基于计算

var howmanytimes = 500/100; 
$('#mytextmultiplied').text(howmanytimes*'whatiwanttowrite'); 

最后一部分显然是错误的。 循环是唯一的选择吗?

回答

3

这里有一个技巧:

var howmanytimes = 500/100; 
var repeatedText = (howmanytimes < 1) ? '' : new Array(howmanytimes + 1).join(whatiwanttowrite); 
$('#mytextmultiplied').text(repeatedText); 

以上技术是不是最快的。为了更有效(但较长的代码明智)技术,看到这些类似的问题的答案:

有一天,你将能够使用String.prototype.repeat

0

你需要一个for循环是这样的:fiddle

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 />"); 
}