首页 > 解决方案 > 为什么 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

标签: javascriptarraysstringreplace

解决方案


想象word = "butter"i=2。然后这一行:

word.replace(word[i], word[i].toUpperCase())

将替换所有出现的twith T,导致word = "buTTer".


推荐阅读