首页 > 解决方案 > 返回相反字母的函数

问题描述

我想编写一个返回交替字符的函数,例如:

"hello world".toAlternatingCase() === "HELLO WORLD"
"HELLO WORLD".toAlternatingCase() === "hello world"
"HeLLo WoRLD".toAlternatingCase() === "hEllO wOrld"

这是我的尝试

const alternatingCase = function (string) {
  let newword = "";

  for (i = 0; i<string.length; i++) {
     if (string.charAt(i).toUpperCase())
    {
    newword+= string.charAt(i).toLowerCase()
    }

   else 
   {
   newword+=string.charAt(i).toUpperCase()
   }
  }
  return newword  
}

调用时,不幸的是,该函数只返回字符串本身,但不确定我做错了什么,非常感谢阅读甚至帮助!

标签: javascript

解决方案


您需要检查字符是否为大写,然后取小写。

不要忘记声明所有变量。

这种方法使用条件(三元)运算符?:,其中条件用于返回两个不同的表达式。

const alternatingCase = function(string) {
    let newword = "";

    for (let i = 0; i < string.length; i++) {
        let character = string[i];
        newword += character === character.toUpperCase()
            ? character.toLowerCase()
            : character.toUpperCase();
    }
    return newword;
}

console.log(alternatingCase('Test'));

如果确实需要将该函数用作字符串的原型,则需要将函数分配给String.prototype所需的方法。为此,您需要寻址this, 以获取字符串的值。

String.prototype.alternatingCase = function() {
    let newword = "";

    for (let i = 0; i < this.length; i++) {
        let character = this[i];
        newword += character === character.toUpperCase()
            ? character.toLowerCase()
            : character.toUpperCase();
    }
    return newword;
}

console.log('Test'.alternatingCase());


推荐阅读