您能解释一下这段代码是如何工作的吗?
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, index) + character + this.substr(index+character.length)
我已经读过这个:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr .我来这里是因为我不明白那个 return 语句以及它到底在做什么。
最佳答案
假设您执行 "thisisatest".replaceAt(3, "h")
。
然后...
this.substr(0, index)
返回"thi"
:即"thisisatest"
的前 3 个字符
字符
返回"h"
this.substr(index+character.length)
返回"isatest"
:即"thisisatest"
的所有字符,从位置开始4
所以,当你结合这个时,你会得到 "thihisatest"
关于javascript - 这个 replaceAt 函数是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45148658/