Hi, THIS WORKS.
But maybe you did it on another way, so share yours here, or give me your advices.
Thanks guys!!!
function repeatStringNumTimes(str, num) {
// repeat after me
var result=[""];
if (num>0){
for (var i=; i<(num);i++){
result.push(str);
}
result.shift();
return result.join("");
}
else {
return “”;
}
What you did is perfectly fine and I think I wrote something similar the first time around. The only problem is that it is rather long. It’s not an issue now but if you ever need to deal with something more complex, read up on some of the string functions. It might save you a lot of time and effort. This is a one line solution to the same problem:
function repeatStringNumTimes(str, num) {
return num > 0 ? str.repeat(num) : '';
}
@mkarabashev
Elegant and brief, nice. I would be careful using it, though. string.prototype.repeat is part of ecmascript 6 and not supported on all common browsers (safari mac/ios, android, see http://kangax.github.io/compat-table/es6/).
I use this ugly thing:
function repeatStringNumTimes(str, num) {
return new Array(num+1).join(str);
}
Nice … struggled understanding what new Array(num+1) did …tried it myself to see what it did but still couldn’t figure out why it works … so googled a bit and found “The new keyword only complicates the code. It can also produce some unexpected results:” ….var points = new Array(40);// Creates an array with 40 undefined elements !!! .
so in my console i type and enter new Array(40) and get back [ undefined * 40 ] so now i understand the result is gotten by using a glitch … lol nice how did you come up with the join() part. Anyway really like this answer,
function repeatStringNumTimes(str, num) {
// repeat after me
var conc = [];
if (num <= 0) {
return “”;
}else {
for (var i = 0; i < num; i++) {
conc += str;
}
}
return conc;
}