简体   繁体   English

JavaScript:为什么此代码不起作用?

[英]JavaScript: Why This Code Doesn't Work?

I am trying to create an text encrypter, but when i entered this code, nothing happens.我正在尝试创建一个文本加密器,但是当我输入此代码时,没有任何反应。 What is wrong with my code?我的代码有什么问题?

function Encrypt(txt) {
var chars = {'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'}
for (i = 0; i < txt.length; i++) {
    var chr = txt.charAt(i);
    var pos = chars.indexOf(chr);
    if (pos == chars.length) {
        pos = 0;
    }
    else {
        pos = pos++
    }
    txt.charAt(i) = chars[pos];
}
alert(txt);
}

You need你需要

  • array [] instead of object {} ,数组[]而不是对象{}
  • some declared variables一些声明的变量
  • an empty result string newText , a string is read only with the character access一个空的结果字符串newText ,一个字符串是只读的,只有字符访问
  • a valid check if the letter is not in the array如果字母不在数组中,则进行有效检查
  • increment pos without assignment.增加pos而不赋值。
  • append the result string with the encoded character用编码字符附加结果字符串

 function Encrypt(txt) { var chars = ['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'], i, newText = '', chr, pos; for (i = 0; i < txt.length; i++) { chr = txt[i]; pos = chars.indexOf(chr); if (!~pos) { pos = 0; } else { pos++; } newText += chars[pos]; } document.write(newText); } Encrypt('test');

Because this is not an array, but object... and object has to have "index" : "value" structure.因为这不是数组,而是对象......并且对象必须具有"index" : "value"结构。

Change this:改变这个:

var chars = {'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'}

to this:对此:

var chars = ['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']

Not considering the errors well described in the other answers, my proposal to encrypt a string is:不考虑其他答案中描述的错误,我对字符串加密的建议是:

 function Encrypt(txt) { var chars = ['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']; var txtResult = txt.split('').map(function(val) { var pos = chars.indexOf(val); return chars[(pos == chars.length) ? 0 : (pos + 1)]; }).join(''); document.write(txtResult); } Encrypt('gaemaf');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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