How does this replaceAt function work?

前端 未结 4 1702
栀梦
栀梦 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 16:00

    Lets imagine this easy case:

    "0123456789". replaceAt(2/*index*/,"000"/*character*/)
    

    Then this happens:

    this.substr(0, index/*2*/)//"01"
     + character //"000"
     + this.substr(index/*2*/+character.length/*3*/)//"56789"
    

    Output:

    0100056789
    

提交回复
热议问题