简体   繁体   中英

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

I am trying to create a Caesar cipher that permanently shifts by 3 and deals with the end of the array using modularisation. Currently, when I run the function it outputs the letters as undefined and I'm not entirely sure why.

 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>

You are not looking for the index. If you entered "A" You are looking for letters["A"] . The array code is not going to find the index with A in it. You need to use indexOf to find it. You are also not looping through the whole array because of the -1 in the length check.

 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>

maybe this simple script will help, just insert on your file

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(rot13("COBB"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM