我该如何修复这个消息解码器/编码器?

huangapple go评论85阅读模式
英文:

How can i fix this message decoder/encoder?

问题

这是一个用JS编写的用于在网页中对消息进行编码和解码的脚本。当我解码消息时,它只返回"undefined(消息的第一个字母)undefinedundefined....."。我知道代码很混乱,我是在凌晨3点写的。请帮帮我,我对JS相当新手。

let dstring = "";
let estring = "";
let letter = "";
let letternum = 0;
let decodedtext = "";
let encodedtext = "";
let currentdt = "";
let currentcharat = 0;

const encoded = [
  "lsdjf",
  "flwek",
  "sdlfj",
  "pjnse",
  "dsfnn",
  "dsnfe",
  "sjndv",
  "sdfew",
  "sdfjn",
  "sfnkh",
  "ædpfk",
  "qpwkd",
  "sorif",
  "efjnf",
  "pijgn",
  "sijfb",
  "feuwh",
  "renfv",
  "soduh",
  "osdnv",
  "ksdjn",
  "tonrn",
  "frjng",
  "fjenw",
  "fnkrj",
  "vrejl",
  "fgwei"
];
alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');

function find(input) {
  for (let i = 0; i < encoded.length; i++) {
    if (input === encoded[i]) {
      return alphabet[i];
    }
  }
}

function encode() {
  estring = prompt("输入要编码的字符串,只能包括非大写字母A-Z或空格");
  for (i = 0; i < estring.length; i++) {
    letter = estring.charAt(i);
    if (letter.charCodeAt(0) === 32) {
      letternum = 26;
    } else {
      letternum = letter.charCodeAt(0) - 97
    }
    encodedtext = encodedtext + encoded[letternum];
  }
  alert(encodedtext)
}

function decode() {
  decodedtext = "";
  dstring = prompt("输入要解码的字符串");
  for (l = 0; l < dstring.length / 5; l++) {
    currentdt = "";
    for (i = 0; i < 5; i++) {
      currentdt = currentdt + dstring.charAt(l * i);
    }
    decodedtext = decodedtext + find(currentdt)
  }
  alert(decodedtext);
}

encode();
decode();

所以,正如我所说的,当尝试解码类似"soduhksdjnsoduhundefinedsdlfjpijgnpjnsedsfnn"(这将翻译成"code")的内容时,它只返回undefinedCundefinedundefined...... 我尝试过许多方法,我的代码一开始的工作方式与现在完全不同,使用字符"|"标记字母的结束,字符"§"标记消息的结束。

英文:

Uhm so basically this is a script for encoding and decoding a message in a webpage using JS. When i decode a message it just returns "undefined(first letter of message)undefinedundefined.....". I know the code is messy, wrote this at like 3 am. Please help. Can't find the problem, pretty new to JS.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let dstring = &quot;&quot;;
let estring = &quot;&quot;;
let letter = &quot;&quot;;
let letternum = 0;
let decodedtext = &quot;&quot;;
let encodedtext = &quot;&quot;;
let currentdt = &quot;&quot;;
let currentcharat = 0;
const encoded = [
&quot;lsdjf&quot;,
&quot;flwek&quot;,
&quot;sdlfj&quot;,
&quot;pjnse&quot;,
&quot;dsfnn&quot;,
&quot;dsnfe&quot;,
&quot;sjndv&quot;,
&quot;sdfew&quot;,
&quot;sdfjn&quot;,
&quot;sfnkh&quot;,
&quot;&#229;dpfk&quot;,
&quot;qpwkd&quot;,
&quot;sorif&quot;,
&quot;efjnf&quot;,
&quot;pijgn&quot;,
&quot;sijfb&quot;,
&quot;feuwh&quot;,
&quot;renfv&quot;,
&quot;soduh&quot;,
&quot;osdnv&quot;,
&quot;ksdjn&quot;,
&quot;tonrn&quot;,
&quot;frjng&quot;,
&quot;fjenw&quot;,
&quot;fnkrj&quot;,
&quot;vrejl&quot;,
&quot;fgwei&quot;
];
alphabet = &#39;abcdefghijklmnopqrstuvwxyz&#39;.split(&#39;&#39;);
function find(input) {
for (let i = 0; i &lt; encoded.length; i++) {
if (input === encoded[i]) {
//alert(alphabet[i]); (for debugging)
return alphabet[i];
}
}
}
function encode() {
estring = prompt(&quot;enter a string to encode, can only include non capital letters A-Z or SPACE&quot;);
for (i = 0; i &lt; estring.length; i++) {
letter = estring.charAt(i);
if (letter.charCodeAt(0) === 32) {
letternum = 26;
} else {
letternum = letter.charCodeAt(0) - 97
}
encodedtext = encodedtext + encoded[letternum];
}
alert(encodedtext)
}
function decode() {
decodedtext = &quot;&quot;;
dstring = prompt(&quot;enter a string to decode&quot;);
for (l = 0; l &lt; dstring.length / 5; l++) {
currentdt = &quot;&quot;;
for (i = 0; i &lt; 5; i++) {
currentdt = currentdt + dstring.charAt(l * i);
}
decodedtext = decodedtext + find(currentdt)
}
alert(decodedtext);
}
encode();
decode();

<!-- end snippet -->

So as I said, when trying to decode something like "soduhksdjnsoduhundefinedsdlfjpijgnpjnsedsfnn" (which would translate to "code") it just returns undefinedCundefinedundefined...... I've tried a number of methods, my code worked in a very different way at first with the character "|" marking where a letter ends and the character "§" marking when the message ended.

答案1

得分: 1

首先,<code> 标签中的文本 soduhksdjnsoduhundefinedsdlfjpijgnpjnsedsfnn 并不是解码器的有效输入,其中包含 undefined。不清楚您是如何使用输入 code 来生成这个文本的,因为编码器实际上为 code 生成了 sdlfjpijgnpjnsedsfnn 的输出。

其次,您的索引逻辑是不正确的:

dstring.charAt(l*i)

l0 时,您会在内部循环的所有 5 次迭代中都执行 dstring.charAt(0)。当 l 为 1 时,您将获得输入的前 5 个字符,但当 l2 时,您将访问索引 02468,可以看到,索引是重复的。这会导致构造出的 currentdt 值无法在 find(currentdt) 中找到,因为 find 在搜索的 encoded 数组中找不到对应值,最终导致 undefined 值。

您真正想要做的是根据已经计算的块的数量(l*5)对 i 进行偏移:
应该是:

dstring.charAt((l*5)+i)

此外,您的 alphabet 数组/字符串缺少空格字符 。当您使用空格编码的 alphabet 运行 find() 时,您将尝试搜索索引 26 的字符,但当前这个索引不存在。您应该将第 26 个字符设置为一个空格,以使解码器正确处理空格字符。另外,这里无需将字符串转换为数组。对字符串使用方括号表示法 [i] 即可正常工作:

'abcdefghijklmnopqrstuvwxyz ';
                           ^--- 在第 26 个索引处添加了空格

最后,使用 for(l = 0; ...)for(i = 0; ...) 创建的循环变量意味着 li 是全局变量,因为您没有使用 varlet 来定义它们。虽然这不会在您的代码中造成太大问题,但它可能会在以后导致问题,所以最好确保您使用 varlet

let dstring = "";
let estring = "";
let letter = "";
let letternum = 0;
let decodedtext = "";
let encodedtext = "";
let currentdt = "";
let currentcharat = 0;
const encoded = [ "lsdjf", "flwek", "sdlfj", "pjnse", "dsfnn", "dsnfe", "sjndv", "sdfew", "sdfjn", "sfnkh", "ådpfk", "qpwkd", "sorif", "efjnf", "pijgn", "sijfb", "feuwh", "renfv", "soduh", "osdnv", "ksdjn", "tonrn", "frjng", "fjenw", "fnkrj", "vrejl", "fgwei" ];
// 更新为使用 `const`,避免意外覆盖 `alphabet`。
// 也删除了 `.split()`,因为它不是必需的,并添加了空格。
const alphabet = 'abcdefghijklmnopqrstuvwxyz '; 

function find(input) {
  for (let i = 0; i < encoded.length; i++) {
    if (input === encoded[i]) {
      return alphabet[i];
    }
  }
}
function encode() {
  estring = prompt("输入要编码的字符串,只能包含小写字母 A-Z 或空格");
  for (let i = 0; i < estring.length; i++) {
    letter = estring.charAt(i);
    if (letter.charCodeAt(0) === 32) {
      letternum = 26;
    } else {
       letternum = letter.charCodeAt(0) - 97
    } 
    encodedtext = encodedtext + encoded[letternum];
  }
  alert(encodedtext);
}
function decode() {
  decodedtext = "";
  dstring = prompt("输入要解码的字符串", "sdlfjpijgnpjnsedsfnn");
  for (let l = 0; l < dstring.length/5; l++) { // 添加了 `let`
    currentdt = "";
    for (let i = 0; i < 5; i++) { // 添加了 `let` 
      currentdt = currentdt + dstring.charAt((l*5)+i); // 更改了偏移的计算
    }
    decodedtext = decodedtext + find(currentdt)
  }
  alert(decodedtext);
}
decode();
英文:

Firstly, <code>soduhksdjnsoduh<strong>undefined</strong>sdlfjpijgnpjnsedsfnn</code> isn't a valid input for your decoder, it has undefined in its text. It's not clear how you produced this with an input of code as the encoder actually produces an output of sdlfjpijgnpjnsedsfnn for code.

Next, your indexing logic isn't correct:

dstring.charAt(l*i)

When l is 0, you'll be doing dstring.charAt(0) for all 5 iterations of your inner loop. When l is 1, you'll get the first 5 characters of your input, when it's 2 however, you'll then be accessing indexes 0, 2, 4, 6, 8. As you can see, you're repeating indexes. This leads to you constructing invalid currentdt values that when passed to find(currentdt), can't be found in the encoded array that find searches, leading to the undefined values.

What you really want to be doing is offseting i with + based on the number of chunks you've already computed (l*5):

It should be:

dstring.charAt((l*5)+i)

In addition to this, your alphabet array/string is missing a space character. When you run find() with the space encoding alphabet for the space fgwei encoding you'll end up searching for the character at index 26, which doesn't exist currently. You should make the 26th character a space for your decoder to work correctly with space characters. In addition to this, there is no need to turn your string into an array here. Indexing with bracket notation [i] works fine on strings:

&#39;abcdefghijklmnopqrstuvwxyz &#39;;
                           ^--- space added here at the 26th index.

Lastly, your loop variables created with for(l = 0; ...) and for(i = 0; ...) mean l and i are global as you're not defining them using var or let. While this doesn't change much in your code, it could easily break things down the line, so it's best to ensure you use var or let:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let dstring = &quot;&quot;;
let estring = &quot;&quot;;
let letter = &quot;&quot;;
let letternum = 0;
let decodedtext = &quot;&quot;;
let encodedtext = &quot;&quot;;
let currentdt = &quot;&quot;;
let currentcharat = 0;
const encoded = [ &quot;lsdjf&quot;, &quot;flwek&quot;, &quot;sdlfj&quot;, &quot;pjnse&quot;, &quot;dsfnn&quot;, &quot;dsnfe&quot;, &quot;sjndv&quot;, &quot;sdfew&quot;, &quot;sdfjn&quot;, &quot;sfnkh&quot;, &quot;&#229;dpfk&quot;, &quot;qpwkd&quot;, &quot;sorif&quot;, &quot;efjnf&quot;, &quot;pijgn&quot;, &quot;sijfb&quot;, &quot;feuwh&quot;, &quot;renfv&quot;, &quot;soduh&quot;, &quot;osdnv&quot;, &quot;ksdjn&quot;, &quot;tonrn&quot;, &quot;frjng&quot;, &quot;fjenw&quot;, &quot;fnkrj&quot;, &quot;vrejl&quot;, &quot;fgwei&quot; ];
// updated to use `const`, avoids potentially overwriting `alphabet` unintentionally.
// Also remove `.split()` as it&#39;s not needed and added space
const alphabet = &#39;abcdefghijklmnopqrstuvwxyz &#39;; 
function find(input) {
for (let i = 0; i &lt; encoded.length; i++) {
if (input === encoded[i]) {
return alphabet[i];
}
}
}
function encode() {
estring = prompt(&quot;enter a string to encode, can only include non capital letters A-Z or SPACE&quot;);
for (let i = 0; i &lt; estring.length; i++) {
letter = estring.charAt(i);
if (letter.charCodeAt(0) === 32) {
letternum = 26;
} else {
letternum = letter.charCodeAt(0) - 97
} 
encodedtext = encodedtext + encoded[letternum];
}
alert(encodedtext);
}
function decode() {
decodedtext = &quot;&quot;;
dstring = prompt(&quot;enter a string to decode&quot;, &quot;sdlfjpijgnpjnsedsfnn&quot;);
for (let l = 0; l &lt; dstring.length/5; l++) { // added `let`
currentdt = &quot;&quot;;
for (let i = 0; i &lt; 5; i++) { // added `let` 
currentdt = currentdt + dstring.charAt((l*5)+i); // changed computation for offset
}
decodedtext = decodedtext + find(currentdt)
}
alert(decodedtext);
}
decode();

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年6月1日 18:52:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76381150.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定