How do I generate 'h' x n in javascript? [duplicate]
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;
}
精彩评论