How does this replaceAt function work?

前端 未结 4 1582
栀梦
栀梦 2021-01-13 15:18

Could you please explain how this piece of code works?

String.prototype.replaceAt = function(index, character) {
    return this.substr(0, index) + characte         


        
4条回答
  •  遥遥无期
    2021-01-13 15:43

    this.substr is a function that operates on a string and returns a 'sub string' of the string. See a tutorial here: https://www.w3schools.com/jsref/jsref_substr.asp

    So what replaceAt is doing is operating on a string and replacing the character at the target index, index, with the new substring, character. Indeed the passed character does not have to be only one character but could be multiple, like abcd. It is rather poorly named.

    For more detail, using substr(), it is taking the first part of the string from index 0 to index, adding the 'character/string' passed to the function, and then taking the rest of the string from index index+character.length onwards. Note that substr has an optional parameter which is used in the first call (this.substr(0,index)).

提交回复
热议问题