javascript - JS在字符串中每隔一个字符切换大小写
问题描述
该函数应该接受一个字符串并每隔一个字符切换一次的大小写。例如:
input: 'HelloWorld' output: 'HElLowoRlD'
input: 'abcdefg' output: 'aBcDeFg'
input: 'TONYmontana' output: 'ToNymOnTaNa'
我的功能不起作用,为什么?
function switchCase(text) {
for (let i = 0; i < text.length; i++) {
if (i % 2 !== 0) {
if (text[i] === text[i].toLowerCase()) {
text[i] = text[i].toUpperCase();
} else {
text[i] = text[i].toLowerCase();
}
}
}
return text;
}
解决方案
您应该将新值存储在字符串中并从函数中返回:
function secondCase(text) {
let newValue = ''; // declare a variable
for (let i = 0; i < text.length; i++) {
if(i % 2 !== 0) {
if (text[i] === text[i].toLowerCase()) {
newValue += text[i].toUpperCase(); // concatenate the modified letter
}
else {
newValue += text[i].toLowerCase(); // concatenate the modified letter
}
}
else newValue += text[i]; // concatenate the unmodified letter
}
return newValue; // return
}
console.log(secondCase('HelloWorld'));
console.log(secondCase('abcdefg'));
console.log(secondCase('TONYmontana'));
推荐阅读
- java - 将 android {} 块放入 kotlin dsl build.gradle.kts 的项目扩展中
- javascript - 有没有办法让我网站的所有外部链接出现在反应的新标签中?
- django - 如何在 django 的单个字段上从多个模型创建外键
- python - 在 tkinter 中将变量从 GUI 写入文本文件
- r - 错误:尝试运行 vuong() 函数时,未为此 S4 类定义 $ 运算符
- git - 如何创建一个 cron 作业,该作业将在每个星期五提交我的存储库中的所有更改
- python - 绘制底图时Python“EPSG代码未知”?
- c - 哪些隐式声明是允许/有效的?
- python - 熊猫 - 从函数中排除第一行和最后一行 - 日期时间
- reactjs - 如何更改 gatsby 站点地图的 url?