简体   繁体   中英

javascript array join() method

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM