根据计算多次插入相同的文本字符串[重复]

时间:2021-11-07 21:28:35

This question already has an answer here:

这个问题在这里已有答案:

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:

上述技术并不是最快的。要获得更高效(但代码更长)的技术,请参阅以下类似问题中的答案:

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:

上述技术并不是最快的。要获得更高效(但代码更长)的技术,请参阅以下类似问题中的答案:

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