How does this replaceAt function work?

前端 未结 4 1678
栀梦
栀梦 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:46

    Suppose you execute "thisisatest".replaceAt(3, "h").

    Then...

    1. this.substr(0, index) returns "thi" : ie the first 3 characters of "thisisatest"
    2. character returns "h"
    3. this.substr(index+character.length) returns "isatest" : ie all characters of "thisisatest", starting at position 4

    So, when you combine this, you get "thihisatest"

提交回复
热议问题