javascript - 返回相反字母的函数
问题描述
我想编写一个返回交替字符的函数,例如:
"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
}
调用时,不幸的是,该函数只返回字符串本身,但不确定我做错了什么,非常感谢阅读甚至帮助!
解决方案
您需要检查字符是否为大写,然后取小写。
不要忘记声明所有变量。
这种方法使用条件(三元)运算符?:
,其中条件用于返回两个不同的表达式。
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());
推荐阅读
- ggplot2 - R中的增长曲线与标准偏差
- mapbox - 使用 .each 添加多个源和层?
- angular - 如何在 Angular 中提交动态创建的表单
- r - R 中的逻辑回归:glm() 与 rxGlm()
- r - 如何处理线性回归中的缺失值?
- java - 如何将 SceneBuilder 连接到 Netbeans 11,尝试创建新的 Java ant JavaFX FXML 应用程序时出现错误
- haskell - 为什么将 LiftA2 作为方法添加到 Applicative 中?
- java - 处理 - 如何调整形状大小
- r - 多于一密度地块合二为一
- android - ClassNotFoundException Unity android 插件