I came across the below code in one website and I am unable to understand the line commented as "DOUBT". How is the function returning the repeated text by using "new Array(n + 1).join(this)" ?
if (!String.prototype.repeat) {
String.prototype.repeat = function(n) {
return new Array(n + 1).join(this); /* DOUBT */
};
}
alert( "La".repeat(3) );
Output: LaLaLa
2 Answers 2
When you join an array of length n by an argument str, you'll create a new string by inserting n - 1 items of str, such that one is between each array item. Eg:
const arr = ['foo', 'bar', 'baz'];
arr.join(' ')
// results in
// foo bar baz
The new Array(n + 1) creates an array which has length n + 1 but has no elements. These non-existent elements, when converted into a string by .join, result in the empty string.
The this inside String.prototype.repeat is the string the function is being called on. For example:
'foo'.repeat(
results in String.prototype.repeat being called with a this of 'foo'.
So:
new Array(n + 1).join(this)
results in a new string containing n repetitions of this.
Another way of looking at it, if 'x'.repeat(2) is called, the following array is constructed:
// [<empty>, <empty>, <empty>]
// insert 'x' between each element of the array:
// '' + 'x' + '' + 'x' + ''
// result: 'xx'
1 Comment
null values n times with separator fooI am Tigran, and I can answer your question.
There is we polifying repeat method in String class:
if (!String.prototype.repeat) {
String.prototype.repeat = function(n) {
//some code
}
}
There are this - a given string (in this example "La"):
return new Array(n + 1).join(this);
Let's discuss by "La" string, "La".repeat(3) there are this is "La" and n is 3.
new Array(3 + 1) -> [empty ×ばつ 4]
[,,,,].join('La') -> "LaLaLa" (, -> empty)
join is method for converting array to string by given string.
If there are any questions, feel free to ask.