【问题标题】:insert the same text string several times based on calculations [duplicate]根据计算多次插入相同的文本字符串[重复]
【发布时间】:2015-07-12 08:46:35
【问题描述】:

我想在我的代码中插入一个等于计算返回的数字的字母:

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

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

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    你需要一个像这样的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 />");
    }
    

    【讨论】:

      【解决方案2】:

      这里有一个技巧:

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

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

      有一天你可以使用String.prototype.repeat

      【讨论】:

        猜你喜欢
        • 2014-06-17
        • 2021-04-05
        • 1970-01-01
        • 2014-02-06
        • 2010-11-16
        • 2013-06-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多