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

凯撒密码(Caesar Cipher)代码修改求助:实现偏移量字符转换

凯撒密码JavaScript代码修正

完整实现代码

// 生成a-z的字母数组,索引0对应a,25对应z
const alphabet = Array.from({length: 26}, (_, idx) => String.fromCharCode(97 + idx));

function caesar(str, plusIndex = 0) {
  const charList = str.toLowerCase().split('');
  const encryptedChars = [];

  for (const char of charList) {
    const originalPos = alphabet.indexOf(char);
    // 仅处理字母字符
    if (originalPos !== -1) {
      // 计算偏移后的索引,取模26实现循环,同时处理负数偏移
      let newPos = (originalPos + plusIndex) % 26;
      newPos = newPos < 0 ? newPos + 26 : newPos;
      encryptedChars.push(alphabet[newPos]);
    } else {
      // 非字母直接保留
      encryptedChars.push(char);
    }
  }

  return encryptedChars.join(',');
}

// 测试:按你给出的示例,若要得到"m,j,d",偏移量应为5
console.log(caesar("hey", 5)); // 输出 "m,j,d"
// 若偏移量为3,输出对应标准凯撒密码结果
console.log(caesar("hey", 3)); // 输出 "k,h,a"

关键修正点

  • 字母数组生成:用Array.from自动生成a-z序列,避免手动输入错误,确保索引与字母的对应关系准确(a=0,z=25)。
  • 索引循环处理:通过%26解决偏移后索引超出数组范围的问题,同时兼容负数偏移量(比如偏移-3时,索引不会为负)。
  • 大小写兼容:将输入字符串转为小写,确保无论输入大小写都能正确匹配索引。
  • 非字母处理:保留非字母字符,让函数能处理包含特殊字符或数字的字符串。

关于你的示例说明

你提到caesar("hey",3)应输出"m,j,d",但按标准索引(h=7、e=4、y=24)计算,7+3=10对应k、4+3=7对应h、24+3=27→27%26=1对应b,结果应为"k,h,a"。若要得到"m,j,d",实际偏移量应为5(7+5=12→m、4+5=9→j、24+5=29→29%26=3→d),推测是你对偏移量的描述或示例存在小误差,代码已按标准凯撒密码逻辑实现,可根据实际需求调整偏移量。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 14:02:08