Reputation: 973
Why below block of code not output string ?
I was expecting it should display abc when we pass num=1.
What I am missing here ?
function repeatStringNumTimes(str, num) {
return Array(num).join(str);
}
console.log(repeatStringNumTimes("abc", 1));
Upvotes: 2
Views: 121
Reputation: 1006
If you only need a string to be repeated n times, use ES6's String.repeat
, like so:
'myString'.repeat(repeatTimes);
Or an array-based solution (not recommended for your problem, though):
new Array(repeatTimes).fill('myString').join('');
If you need ES5 solution, use lodash
fn repeat
:
_.repeat('abc', 2);
Upvotes: 2
Reputation: 386654
You need at least two elements for Array#join
with a separator, because one element is just converted to a string and it does not need any glue.
function repeatStringNumTimes(str, num) {
return Array(num + 1).join(str);
}
console.log(repeatStringNumTimes("abc", 1));
Upvotes: 9