我有这个 IF 说:如果字符串的索引是 == 0 则将其设为大写,但输出是小写的索引 0

I have this IF saying that: if the index of the string is == 0 then make it UpperCase, but the output is index 0 in lowercase

function titleCase(str) {
  let newStr = ''
  
  for(let i = 0; i < str.length; i++){

    if(str[i] == 0){
      newStr += str[i].toUpperCase()//sets the first character of the String to uppercase
    } else if (str[i - 1] == ' '){
      newStr += str[i].toUpperCase();//sets every character that has a space before it to uppercase
    } else {
      newStr += str[i].toLowerCase();//sets any other character to lowercase
    }

  } return newStr 

}


console.log(titleCase("I'm a liTTle tea pot")); // output: i'm A Little Tea Pot

您需要检查第一个索引,即 i 是否为 0,但您正在检查 0 处的字符是否相等,即 I

因为 I 不等于 0 所以它跳过匹配。

所以你需要从

 if(str[i] == 0){

if (i === 0) {

function titleCase(str) {
  let newStr = "";

  for (let i = 0; i < str.length; i++) {
    if (i === 0) {
      newStr += str[i].toUpperCase(); //sets the first character of the String to uppercase
    } else if (str[i - 1] == " ") {
      newStr += str[i].toUpperCase(); //sets every character that has a space before it to uppercase
    } else {
      newStr += str[i].toLowerCase(); //sets any other character to lowercase
    }
  }
  return newStr;
}

console.log(titleCase("I'm a liTTle tea pot"));

if(str[i] == 0) 应该是 if(i === 0) 否则检查字符串中的第一个字符是否为零

此问题与 if 条件有关,因为当前使用的是索引 0 处的值而不是索引 正确的条件是

if(i==0) 

对于第一个 if 条件,您应该将其更改为与 i 进行比较,而不是与 str[i] 进行比较。 str[i] 不等于零,它返回字符串的第一个字符。

if(i == 0){newStr += str[i].toUpperCase();}