开发者

How do I generate 'h' x n in javascript? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible开发者_JAVA技巧 Duplicate:

Repeat String - Javascript

'h' x n;

Here n is a variable, and the generated string should be n times duplicate of h:

hh..h( n occurance of h in all)


Here's a cute way to do it with no looping:

var n = 20;
var result = Array(n+1).join('h');

It creates an empty array of a certain length and then joins all the empty elements of the array putting your desired character between the empty elements - thus ending up with a string of all the same character n long.

You can see it work here: http://jsfiddle.net/jfriend00/PCweL/


String.prototype.repeat = function(n){
  var n = n || 0, s = '', i;
  for (i = 0; i < n; i++){
    s += this;
  }
  return s;
}

"h".repeat(5) // output: "hhhhh"

Something like that perhaps?


If I understood your question following may be the solution.

var n = 10;
var retStr = "";
for(var i=0; i<n; ++i) {
retStr += "h";
}

return retStr;


Try,

function repeat(h, n) {
    var result = h;
    for (var i = 1; i < n; i++)
       result += h;
    return result;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜