Reputation: 821
someone can help me to understand this script:
String.prototype.padLeft = function(width, char) {
var result = this;
char = char || " ";
if (this.length < width) {
result = new Array(width - this.length + 1).join(char) + this;
}
return result;
};
console.log("abc".padLeft(10,"-"));
So.. im extend the object String with a new method. The char parameter is optional (if omitted, the function will use white space) I dont have clear this part:
result = new Array(width - this.length + 1).join(char) + this;
Am i creating a new array with 8 element that are undefined and then separate them with the separetor? Is it correct? Why there is a"+1" in the array definition? Thank you in advance
Upvotes: 0
Views: 911
Reputation: 780984
When you join an array with N
elements, there will be N-1
separators between the elements. The code is using join
to create a string with just N
separators, so you need to give it an array with N+1
elements to account for this.
Upvotes: 1
Reputation: 9451
new Array(width - this.length + 1).join(char)
This ^ is effectively saying "make an empty array with n
number of slots, then join the empty slots together using the char
to separate each empty slot. So, if char = "0"
, and n = 3
, we get 000
.
width - this.length + 1
is used to determine the number of characters needed to be added to beginning of the string.
Then we add that to the beginning of the original string: this
+1
You need the + 1 because of how join works.
new Array(1).join('0') = "" // wrong
new Array(1+1).join('0') = "0" // correct
new Array(2).join('0') = "0" // wrong
new Array(2+1).join('0') = "00" // correct
Upvotes: 1