[英]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你需要
[]
instead of object {}
,[]
而不是对象{}
,newText
, a string is read only with the character accessnewText
,一个字符串是只读的,只有字符访问pos
without assignment.pos
而不赋值。 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.