【问题标题】:toUpperCase not working [duplicate]toUpperCase 不起作用[重复]
【发布时间】:2018-10-16 14:35:34
【问题描述】:

我创建了这段代码,其中大部分都在使用 toUpperCase 例外,它应该使单词的每个第一个字母大写。没有错误,所以我不确定为什么该方法当前不起作用。为什么会这样。

let str ="insert string here"
String.prototype.toCase = function () {
  let arrayWord = str.split("");
  for (let i = 0; i<str.length; i++){
    if (arrayWord[i]===" "){
      arrayWord[i+1].toUpperCase();
    }
    else{
    }
  }
  let result = arrayWord.join("");
  return (result)
};

【问题讨论】:

  • 函数的输出是什么?

标签: javascript loops


【解决方案1】:

toUpperCase 返回修改后的字符串,它不会修改调用它的字符串。

var a = "donald";
var b = a.toUpperCase();

console.log(a) // donald
console.log(b) // DONALD

在这里,我使它可以保持您的代码结构,但它仍然存在一些问题。如果您以后需要,我会输入一个考虑所有极端情况的解决方案。

var str = "donald fauntleroy duck"

var str_array = str.split("");
var ret_str = ""
for(var i=0; i<str_array.length; i++)
    {
    if(i > 0)
        {//avoid checking out of scope
        if(str_array[i-1] === " ")
            {
            ret_str += str_array[i].toUpperCase();
            }
        else
            {
            ret_str += str_array[i];
            }
        }
    }

return(ret_str);

【讨论】:

    【解决方案2】:

    您忘记分配 String#toUpperCase 的结果,因为它返回的是修改后的字符串,而不是处理被调用的字符串。

    ...返回转换为大写的调用字符串值...

    添加一个作业,例如: arrayWord[i + 1] = arrayWord[i + 1].toUpperCase();

    演示

    let str ="insert string here"
    String.prototype.toCase = function () {
      let arrayWord = str.split("");
      for (let i = 0; i < str.length; i++){
        if (arrayWord[i] === " "){
          arrayWord[i + 1] = arrayWord[i + 1].toUpperCase();
        }
        else{
        }
      }
      let result = arrayWord.join("");
      return (result)
    };
    
    console.log(str.toCase());

    【讨论】:

      【解决方案3】:

      设置新值arrayWord[i+1]=arrayWord[i+1].toUpperCase();

      【讨论】:

        【解决方案4】:

        此函数将单词的首字母大写:

        function uppercaseFirstLetter(string) {
            return string.charAt(0).toUpperCase() + string.slice(1);
        }
        
        var output = "";
        
        let str ="insert string here";
        
        str = str.split(' ').forEach(itm => output += uppercaseFirstLetter(itm) + ' ');
        
        console.log(output);

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-04-10
          • 1970-01-01
          • 2021-09-21
          • 2016-06-01
          • 2018-01-04
          相关资源
          最近更新 更多