首页 > 解决方案 > 制作凯撒密码的问题

问题描述

我尝试编写一个 Ceasar Cipher 编码器作为学校的练习。我遇到了一个问题,其中字母 x、y 和 z 未定义。

function txtcipher() {
  var txt = document.getElementById("txt").value;
  var txtlen = txt.length;
  var txtciphered = "";
  var alphabet = "abcdefghijklmnopqrstuvwxyz";
  for (x = 0; x < txtlen; x++) {
    for (y = 0; y < alphabet.length; y++) {
      if (txt[x] === alphabet[y]) {
        txtciphered += alphabet[y + 3];
      }
    }
  }
  document.getElementById("cpher").value = txtciphered;
  console.log(txtciphered);
}
<input id="txt" />
<button onclick="txtcipher()">Check</button><br />
<input type="text" id="cpher" readonly></input>

我该如何解决?

标签: javascript

解决方案


您需要保持在数组的数组长度范围alphabet

代替

y + 3

采用

(y + 3) % alphabet.length

function txtcipher() {
  var txt = document.getElementById("txt").value;
  var txtlen = txt.length;
  var txtciphered = "";
  var alphabet = "abcdefghijklmnopqrstuvwxyz";
  for (x = 0; x < txtlen; x++) {
    for (y = 0; y < alphabet.length; y++) {
      if (txt[x] === alphabet[y]) {
        txtciphered += alphabet[(y + 3) % alphabet.length];
      }
    }
  }
  document.getElementById("cpher").value = txtciphered;
  console.log(txtciphered);
}
<input id="txt"  value="xyzabc"/>
<button onclick="txtcipher()">Check</button><br />
<input type="text" id="cpher" readonly placeholder="abcdef <-- xyzabc"></input>


推荐阅读