【问题标题】:What am I missing regarding the toUpperCase method?关于 toUpperCase 方法,我缺少什么?
【发布时间】:2021-05-23 03:29:17
【问题描述】:

我正在尝试通过toUpperCase 方法将每个单词的首字母大写,而通过toLowerCase 方法将单词的其余部分设为小写。但是我遗漏了一些东西......为什么temp 的值与result[1][0] 不匹配,即使我对两者都使用了该方法?

注意:我知道解决方案的其他方法(mapreplace 等),但我只想使用带有 toUpperCasetoLowerCase 方法的 for 循环。

    function titleCase(str) {
  let regex = /[^0-9\s]+/g;
  var result = str.match(regex);
  let temp = "";
  for (let i = 0; i < result.length; i++) {
    for (let j = 0; j < result[i].length; j++) {
        result[1][0] = result[1][0].toUpperCase();
        temp = result[1][0].toUpperCase();
    }
  }

  console.log(temp); // Output is 'A'
  console.log(result[1][0]); //Output is 'a'
  // Normally 'temp' and 'result[1][0]' should be equal, but one returns a lowercase character and the other an uppercase character.
  return str;
}

titleCase("I'm a little tea pot");

【问题讨论】:

    标签: javascript for-loop uppercase


    【解决方案1】:

    您的问题不在于toUppercase(),而在于参考。

    引用result[1][0]时,为什么要包含0?你已经有了result[1]的第二个字符

    result[1] === 'a'。也不需要包含 [0]。

    更改您的代码,使其如下所示:

    function titleCase(str) {
        let regex = /[^0-9\s]+/g;
        var result = str.match(regex);
        let temp = "";
        
        result[1] = result[1].toUpperCase();
        temp = result[1].toUpperCase();
      
        console.log(temp); // Output is 'A'
        console.log(result[1]); //Output is also 'A'
        // both now equals capital A
        return str;
      }
      
      titleCase("I'm a little tea pot");

    编辑: 将函数更新为大写单词的第一个字母。

    我们可以使用 ES6,这会变得非常简单:

    const capitalize = (string = '') => [...string].map((char, index) => index ? char : char.toUpperCase()).join('')  
    

    使用它:capitalize("hello") 返回“Hello”。

    首先,我们使用扩展运算符将字符串转换为数组,以将每个字符单独获取为字符串。然后我们映射每个字符以获取索引以将大写应用于它。索引 true 表示不等于 0,因此 (!index) 是第一个字符。然后我们对其应用大写函数,然后返回字符串。


    如果您想要更面向对象的方法,我们可以这样做:

    String.prototype.capitalize = function(allWords) {
        return (allWords) ?
        this.split(' ').map(word => word.capitalize()).join(' ') : 
        return this.charAt(0).toUpperCase() + this.slice(1);
    }
    

    使用它:"hello, world!".capitalize(); 返回“Hello, World”

    我们将短语分解为单词,然后递归调用,直到将所有单词大写。如果 allWords 未定义,则仅将第一个单词大写,表示整个字符串的第一个字符。

    【讨论】:

    • 对此我很抱歉,我从代码中删除了 for 循环,然后我忘记了将其删除。我刚刚编辑了帖子。你能检查一下吗,请再看一遍
    • 很抱歉,我很难理解您的代码。它应该做什么?为什么要执行 2 个 for 循环,但对其中的值进行硬编码?出于这个原因,我的答案将保持不变,即使在 for 循环中
    • 我使用了两个循环,因为我需要将单词的其余部分设为小写。
    • 无需使用 2 个循环。我正在更新我的答案
    • 首先感谢您的回答,但是,我知道我的解决方案的其他方法(地图,替换...)。但是,我只想使用 for-loop 和 toUpperCase() 和 toLowerCase() 方法...
    【解决方案2】:

    我试图更改字符串中的特定字符,但字符串在 JS 中是不可变的,所以这没有意义。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-02
      • 2014-02-17
      • 1970-01-01
      相关资源
      最近更新 更多