javascript - 制作凯撒密码的问题
问题描述
我尝试编写一个 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>
我该如何解决?
解决方案
您需要保持在数组的数组长度范围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>
推荐阅读
- java - 如何修复“使用独立于操作系统的路径‘META-INF/INDEX.LIST’找到多个文件”?
- c# - ASP.NET Web API 连接到 MySQL 数据库
- java - 如何使用 Java 使用 S3 对象 ARN 访问 S3 对象
- java - 在 MS 365 开发计划帐户中使用 disabledPlans 的 AssignedLicense
- jenkins - 如何在 jenkins maven 工作中禁止特定的 jar 版本?
- node.js - 如何在 PostgreSQL GEOMETRY 字段上创建空间索引?
- android - android studio颤振中未显示android项目结构
- html - 如何使用 boostrap 添加侧组输入?
- reactjs - React-Player 媒体控件不适用于 react .js 的较小宽度,例如 100px
- android - 使用 Chrome Devtools CSS Grid 检查器进行远程 webview