2
同一文本字符串的好幾次我想插入等於我的代碼中通過計算返回的數字一個字母:插入基於計算
var howmanytimes = 500/100;
$('#mytextmultiplied').text(howmanytimes*'whatiwanttowrite');
最後一部分顯然是錯誤的。 循環是唯一的選擇嗎?
同一文本字符串的好幾次我想插入等於我的代碼中通過計算返回的數字一個字母:插入基於計算
var howmanytimes = 500/100;
$('#mytextmultiplied').text(howmanytimes*'whatiwanttowrite');
最後一部分顯然是錯誤的。 循環是唯一的選擇嗎?
這裏有一個技巧:
var howmanytimes = 500/100;
var repeatedText = (howmanytimes < 1) ? '' : new Array(howmanytimes + 1).join(whatiwanttowrite);
$('#mytextmultiplied').text(repeatedText);
以上技術是不是最快的。爲了更有效(但較長的代碼明智)技術,看到這些類似的問題的答案:
有一天,你將能夠使用String.prototype.repeat
你需要一個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 />");
}