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

JavaScript Rot13函数功能异常,求助代码问题排查

问题排查与修复

你写的Rot13函数目前只处理了大写英文字母,完全漏掉了小写字母的加密逻辑!这就是测试输入"Ruby is cool!"返回"Euby is cool!"的原因——"Ruby"里的"u"、"b"、"y"都是小写,代码里没有对应的处理分支,所以直接原样返回了。

问题点拆解

你的代码只判断了ASCII 65-90(大写A-Z)的情况:

  • A-M(65-77):加13
  • N-Z(78-90):减13
    但完全没处理ASCII 97-122(小写a-z)的场景,导致小写字母直接跳过加密步骤。

修复后的代码

function rot13(message){ 
  var solved = ""; 
  for (var i=0; i<message.length; i++){ // 给循环变量i加var声明,避免全局变量污染
    var asciiNum = message[i].charCodeAt(); 
    // 处理大写字母
    if (asciiNum >= 65 && asciiNum <= 77) { 
      solved += String.fromCharCode(asciiNum + 13); 
    } else if (asciiNum >= 78 && asciiNum <= 90) { 
      solved += String.fromCharCode(asciiNum - 13); 
    } 
    // 新增:处理小写字母
    else if (asciiNum >= 97 && asciiNum <= 109) { 
      solved += String.fromCharCode(asciiNum + 13); 
    } else if (asciiNum >= 110 && asciiNum <= 122) { 
      solved += String.fromCharCode(asciiNum - 13); 
    } 
    // 其他字符原样返回
    else { 
      solved += message[i]; 
    } 
  } 
  return solved; 
}

额外优化小提示

  1. 给循环变量i加上var声明(或者用let,如果环境支持ES6+),避免不小心创建全局变量。
  2. 可以利用Rot13的特性简化判断逻辑,不管大小写,都能通过模运算减少重复代码,比如:
function rot13(message){
  return message.split('').map(char => {
    const code = char.charCodeAt();
    if (code >= 65 && code <= 90) {
      return String.fromCharCode((code - 65 +13) %26 +65);
    } else if (code >=97 && code <=122) {
      return String.fromCharCode((code -97 +13)%26 +97);
    }
    return char;
  }).join('');
}

现在用测试输入"Ruby is cool!"测试修复后的代码,就能得到正确的"Ehol vf pbby!"啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 18:58:13