javascript - 为什么 js .replace() 在双字母中工作不正确?
问题描述
我试图编写在奇怪的情况下返回字符串的函数。例如:
toWeirdCase("String") //StRiNg
因此,它似乎有效,但并非在所有情况下都有效。当我们将字符串与双字母函数返回时,会返回一些非常奇怪的东西(没有双精度都很好):
我不需要其他方式来实现,我需要解释我的功能有什么问题。有人可以吗?
function toWeirdCase(string) {
let arrSentence = string.toLowerCase().split(' ');
arrSentence = arrSentence.map((word) => {
for (let i = 0; i < word.length; i++) {
if (i % 2 == false) {
word = word.replace(word[i], word[i].toUpperCase())
}
}
return word
});
arrSentence = arrSentence.join(' ');
return arrSentence
}
console.log(toWeirdCase('Loooooks')) //LOOoooKs
console.log(toWeirdCase('Looks')) //LOokS
解决方案
想象word = "butter"
和i=2
。然后这一行:
word.replace(word[i], word[i].toUpperCase())
将替换所有出现的t
with T
,导致word = "buTTer"
.
推荐阅读
- sed - 如何根据在每一行上找到的值将文件(使用 sed)拆分为多个文件?
- c# - 在 WPF 应用程序中加载大尺寸图像(超过 2GB)
- heroku - 优雅地缩小heroku web dynos
- machine-learning - 如何构建 CNN 自动编码器?
- python-3.x - 当它小于范围时在我的文本文件中显示元素?
- python - Pygame - 两个对象之间的碰撞不起作用
- excel - Excel 公式在不知道原因的情况下被删除
- google-apps-script - 谷歌表格到火力基地
- json - 为什么返回所有 id 而不是一个匹配的搜索条件
- java - 根据第二个地图中键的顺序对地图进行排序