如何使用 Javascript 中的 for 循环创建移位 3 的凯撒密码?

How do I create a Caesar Cipher that shifts by 3 using a for loop in Javascript?

我正在尝试创建一个永久移动 3 并使用模块化处理数组末尾的凯撒密码。目前,当我 运行 函数输出未定义的字母时,我不完全确定为什么。

function caesarCipher() {
  let letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];
  let shift = 3;
  let outputString = "";

  let userString = document.getElementById("input").value;

  for (count = 0; count < userString.length - 1; count++) {
    let character = userString[count];
    let letterIndex = letters[character];
    let newIndex = (letterIndex + shift) % 26;
    let newCharacter = letters[newIndex];
    outputString = outputString + newCharacter;
  }

  document.getElementById("output").value = outputString;
}
<div id="alignment">
  <label for="input">String Input</label>
  <input type="text" id="input" placeholder="Unciphered">
  <input type="submit" id="button" value="CIPHER STRING" onclick="caesarCipher()">
  <label for="input">String Output</label>
  <input type="text" id="output" placeholder="Ciphered">
</div>

您不是在查找索引。如果您输入了“A”,您正在寻找 letters["A"]。数组代码不会找到其中包含 A 的索引。您需要使用 indexOf 来找到它。由于长度检查中的 -1,您也没有遍历整个数组。

function caesarCipher() {
  let letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];
  let shift = 3;
  let outputString = "";

  let userString = document.getElementById("input").value;

  for (count = 0; count < userString.length; count++) {
    const character = userString[count];
    const letterIndex = letters.indexOf(character);
    const newIndex = (letterIndex + shift) % 26;
    const newCharacter = letters[newIndex];
    outputString = outputString + newCharacter;
  }

  document.getElementById("output").value = outputString;
}
<div id="alignment">
  <label for="input">String Input</label>
  <input type="text" id="input" placeholder="Unciphered">
  <input type="submit" id="button" value="CIPHER STRING" onclick="caesarCipher()">
  <label for="input">String Output</label>
  <input type="text" id="output" placeholder="Ciphered">
</div>

也许这个简单的脚本会有所帮助。只需将其插入您的文件即可。

function rot3(str) {
  let regex = /[\W]/g
  return str.split('').map(i => regex.test(i)
  ? i
  : String.fromCharCode(i.charCodeAt() + 3 > 90 
    ? (i.charCodeAt() + 3 - 26) 
    : i.charCodeAt() + 3)
  ).join("")
}

console.log(rot3("COBB"))