Title Case a Sentence 使用 for 循环

Title Case a Sentence using for loop

我很快就要完成这个练习了。该指令是将 str 转换为这个新字符串 Here Is My Handle Here Is My Spout.

我的代码正好返回 Here Is My Handle Here Is My Spout,但是当我尝试 console.log(result.split(" ")) 时,它返回了这个 [ '', 'Here', 'Is', 'My', 'Handle', 'Here', 'Is', 'My', 'Spout' ]

我正在尝试删除索引 0 中的空字符串,但我似乎无法删除它。 我也在想,当我在 result 中传递它而不是字符串时,我正在返回 words 的数组?

function titleCase(str) {
  const words = str.toLowerCase().split(" ");
  let result = "";
  for (let word of words) {
let firstCap = word.replace(word[0], word[0].toUpperCase());
 result = result + " " + firstCap;
  }
  console.log(result.split(" "))
  return result;
}

console.log(titleCase("HERE IS MY HANDLE HERE IS MY SPOUT"));

问题在于行:

result = result + " " + firstCap;

result 的值为 "" 时,您不应添加 space 而是添加一个空字符串,如下所示:

result = result + (result.length ? " " : "") + firstCap;

function titleCase(str) {
  const words = str.toLowerCase().split(" ");
  let result = "";
  for (let word of words) {
    let firstCap = word.replace(word[0], word[0].toUpperCase());
    result = result + (result.length ? " " : "") + firstCap;
  }
  console.log(result.split(" "))
  return result;
}

console.log(titleCase("HERE IS MY HANDLE HERE IS MY SPOUT"));

更好的方法是使用 Array#map(),然后使用 Array#join()

function titleCase(str) {
  const words = str.toLowerCase().split(" ");
  return words.map(word => word.replace(word[0], word[0].toUpperCase())).join(" ");
}

console.log(titleCase("HERE IS MY HANDLE HERE IS MY SPOUT"));