Javascript 这个replaceAt函数是如何工作的?

Javascript 这个replaceAt函数是如何工作的?,javascript,Javascript,你能解释一下这段代码是如何工作的吗 String.prototype.replaceAt = function(index, character) { return this.substr(0, index) + character + this.substr(index+character.length); }; function titleCase(str) { var newTitle = str.split(' '); var updatedTitle = [

你能解释一下这段代码是如何工作的吗

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


function titleCase(str) {
    var newTitle = str.split(' ');
    var updatedTitle = [];
    for (var st in newTitle) {
        updatedTitle[st] = newTitle[st].toLowerCase().replaceAt(0, newTitle[st].charAt(0).toUpperCase());
    }
    return updatedTitle.join(' ');
}

titleCase("I'm a little tea pot");
具体来说,到底传递给replaceAt的是什么(我知道它传递了一个索引和一个转换成小写的字符),但是replaceAt对它做了什么呢

所以,在循环的第一次迭代中,它被传递到replaceAt(0,i),对吗?那replaceAt怎么处理这个呢?我就是不明白这句话:

this.substr(0,索引)+字符+this.substr(索引+字符.长度)


我已经读过了:。我来这里是因为我不明白返回语句以及它到底在做什么

让我们想象一下这个简单的例子:

"0123456789". replaceAt(2/*index*/,"000"/*character*/)
然后发生这种情况:

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

0100056789

replaceAt函数只需获取一个字符(本例中为0)的索引,并将其替换为另一个字符(本例中为原始字符的大写版本)。此特定函数只是通过将第一个字符替换为相同的大写字符来对一个字进行标题加粗

提问的行在指定索引this.substr(0,index)的字符前面加上单词的子字符串,因为substr不包括最后一个索引,所以会附加指定的字符
+字符
,并附加单词其余部分的子字符串
+this.substr(index+character.length)

示例“testing”.replaceAt(0,
testing
.charAt(0).toUpperCase());
=''+'T'+'esting'=测试;

此.substr
是一个对字符串进行操作并返回字符串的“子字符串”的函数。请参阅此处的教程:

因此,
replaceAt
所做的是对字符串进行操作,并将目标索引
index
处的字符替换为新的子字符串
character
。实际上,传递的
字符不必只有一个字符,而可以是多个字符,如
abcd
。它的名称相当糟糕

有关详细信息,请使用
substr()
,它将字符串的第一部分从索引
0
提取到
index
,添加传递给函数的“字符/字符串”,然后从索引
index+character.length
提取其余字符串。请注意,
substr
有一个可选参数,在第一次调用中使用(
this.substr(0,index)
)。

假设执行
“thisistest”.replaceAt(3,h)

然后

  • this.substr(0,索引)
    返回
    “thi”
    :即
    “thisistest”的前3个字符
  • 字符
    返回
    “h”
  • this.substr(index+character.length)
    返回
    的“isatest”
    :即从位置4开始的
    thisisatest“
    的所有字符

  • 所以,当你把这些结合起来时,你会得到“thihisatest”

    我读过这篇文章。我来这里是因为我不明白return语句到底是如何工作的。为什么会被否决?OP提供了证据,证明他/她在理解代码方面付出了一些努力,但他/她是来帮忙的。