为什么我的函数首字母大写 return false 与最终结果比较时? Javascript

Why my function of capitalize all first letters return false when is compare with the final result? Javascript

我有这两个函数,可以让每个单词的首字母大写,其余部分小写。

我比较了每个函数的return和最终想要的结果,但是我的函数return false,有map的函数return true。有人知道为什么吗?

let str1 = "I'm a little tea pot"
let str2 = "sHoRt AnD sToUt"
let str3 = "HERE IS MY HANDLE HERE IS MY SPOUT"

function titleCase(str) {
  let toArray = str.split(" ")
  let allCapitalize = ""
  for (let x of toArray) {
    allCapitalize += x.charAt(0).toUpperCase() + x.slice(1).toLowerCase() + " "
  }
  return allCapitalize
}

function titleCaseMap(str) {
  return str.split(" ").map((x) => {
    return x.charAt(0).toUpperCase() + x.slice(1).toLowerCase()
  }).join(" ");
}

console.log(titleCase(str1));
console.log(titleCase(str2));
console.log(titleCase(str3));

console.log(titleCase(str1) === "I'm A Little Tea Pot"); //false
console.log(titleCase(str2) === "Short And Stout"); //false
console.log(titleCase(str3) === "Here Is My Handle Here Is My Spout"); //false

console.log(titleCaseMap(str1))
console.log(titleCaseMap(str2))
console.log(titleCaseMap(str3))

console.log(titleCaseMap(str1) === "I'm A Little Tea Pot"); //true
console.log(titleCaseMap(str2) === "Short And Stout"); //true
console.log(titleCaseMap(str3) === "Here Is My Handle Here Is My Spout"); //true

您的 titleCase 函数在返回行的末尾添加了一个 space。你应该 trim 关闭:

let str1 = "I'm a little tea pot"
let str2 = "sHoRt AnD sToUt"
let str3 = "HERE IS MY HANDLE HERE IS MY SPOUT"

function titleCase(str) {
  let toArray = str.split(" ")
  let allCapitalize = ""
  for (let x of toArray) {
    allCapitalize += x.charAt(0).toUpperCase() + x.slice(1).toLowerCase() + " "
                                                // Well there's your problem ^
  }
  return allCapitalize.trim();
}

console.log(titleCase(str1));
console.log(titleCase(str2));
console.log(titleCase(str3));

console.log(titleCase(str1) === "I'm A Little Tea Pot"); //false
console.log(titleCase(str2) === "Short And Stout"); //false
console.log(titleCase(str3) === "Here Is My Handle Here Is My Spout"); //false

titleCase 函数总是在最后添加一个额外的 space。

您应该更新它,以便在末尾不添加 space。

我将函数更新为:

function titleCase(str) {
    let toArray = str.split(" ")
    let allCapitalize = ""
    for (let i = 0; i < toArray.length; i++) {
        let x = toArray[i];

        if (i > 0) {
            allCapitalize += " ";
        }

        allCapitalize += x.charAt(0).toUpperCase() + x.slice(1).toLowerCase();
    }
    return allCapitalize
}