You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何仅使用for循环实现JavaScript字符串字符大小写反转

大小写反转实现方案

你可以按照以下逻辑实现,仅使用for循环完成需求:

完整代码

let swappedName = "elZerO";
let result = "";

// 仅用for循环遍历所有字符
for (let i = 0; i < swappedName.length; i++) {
  const currentChar = swappedName[i];
  // 判断当前字符大小写后反转
  if (currentChar === currentChar.toUpperCase()) {
    result += currentChar.toLowerCase();
  } else {
    result += currentChar.toUpperCase();
  }
}

console.log(result); // 输出:ELzERo

逻辑说明

  • 先初始化空字符串result,用来存储最终处理后的结果
  • for循环遍历swappedName的每一个字符,遍历次数和字符串长度完全匹配
  • 利用字符的toUpperCase()方法判断原字符大小写:如果字符转大写后和自身相等,说明原字符是大写,转小写后拼接进结果;反之原字符是小写,转大写后拼接
  • 循环结束后result就是符合要求的反转结果

内容的提问来源于stack exchange,提问作者Ahmed Mohsen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 00:00:01